A class is the core concept of object-oriented programming in Python. Below, I will comprehensively introduce how to create and use class objects.
1. Basic Structure and Creation of Classes
1. The Simplest Class
class EmptyClass: pass # Empty class, using pass as a placeholder
# Create object instance
obj = EmptyClass()
print(obj) # Output: <__main__.EmptyClass object at 0x...>
2. Class with Attributes and Methods
class Person: # Class attribute (shared by all instances) species = "Human"
def __init__(self, name, age): # Instance attributes (unique to each instance) self.name = name self.age = age
# Instance method def introduce(self): return f"My name is {self.name}, I am {self.age} years old"
# Class method @classmethod def get_species(cls): return f"Species: {cls.species}"
# Static method @staticmethod def is_adult(age): return age >= 18
# Create objects
person1 = Person("Zhang San", 25)
person2 = Person("Li Si", 17)
print(person1.introduce()) # Output: My name is Zhang San, I am 25 years old
print(Person.get_species()) # Output: Species: Human
print(Person.is_adult(20)) # Output: True
2. Creating and Using Objects
1. Basic Object Operations
class Car: def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year self.mileage = 0
def drive(self, km): self.mileage += km return f"Drove {km} kilometers, total mileage: {self.mileage}km"
def get_info(self): return f"{self.year} {self.brand} {self.model}"
# Create object
my_car = Car("Toyota", "Camry", 2023)
# Access attributes
print(my_car.brand) # Output: Toyota
print(my_car.model) # Output: Camry
# Call methods
print(my_car.get_info()) # Output: 2023 Toyota Camry
print(my_car.drive(100)) # Output: Drove 100 kilometers, total mileage: 100km
print(my_car.drive(50)) # Output: Drove 50 kilometers, total mileage: 150km
2. Dynamically Adding Attributes
class Student: def __init__(self, name): self.name = name
# Create object and dynamically add attributes
student = Student("Wang Wu")
student.age = 20 # Add instance attribute
student.grades = [85, 92, 78] # Add list attribute
print(f"{student.name}, {student.age} years old") # Output: Wang Wu, 20 years old
print(f"Grades: {student.grades}") # Output: Grades: [85, 92, 78]
Summary
Key Points for Creating and Using Class Objects:
-
Defining a Class: Use the
<span>class</span>keyword, including attributes and methods -
Creating an Object: Use
<span>ClassName()</span>to create an instance -
Initialization: The
<span>__init__()</span>method is used to initialize the object -
Method Calls: Use
<span>object.method()</span>to call a method -
Attribute Access: Use
<span>object.attribute</span>to access an attribute
Best Practices:
-
Use meaningful class and method names
-
Maintain single responsibility for classes
-
Use type hints to improve readability
Mastering the creation and use of classes is fundamental to Python’s object-oriented programming, helping you build more modular and maintainable code.
Please open in the WeChat client