1. In Python, a class is a template for creating objects, defining the common attributes (data) and methods (behavior) of the objects; an object is an instance of a class, a concrete implementation of the class.The relationship between classes and objects: a class is like a blueprint for a car, specifying that the car should have wheels and be able to drive; an object is a specific car built according to that blueprint.Key features of classes:(1) Encapsulation: Attributes and methods are encapsulated within the class, and external access is through objects, without needing to concern oneself with the internal implementation.(2) Inheritance: A subclass can inherit attributes and methods from a parent class and extend new functionalities.(3) Polymorphism: Objects of different classes can exhibit different behaviors when calling methods with the same name.2. Class DefinitionClasses are created using the reserved word class, and class names typically start with an uppercase letter. The class definition includes the creation of attributes and the definition of methods.
# Define the Car classclass Car:# Class attributes: color="black" wheel=4# Class method (private function of the class) def drive(self): print("Driving...")
Attributes are created within the class’s indentation scope by directly assigning values to variables (attribute names), while the definition of class methods is similar to defining functions, except they become private functions of the class (i.e., class methods). It is important to note that when defining methods within a class, the first parameter must always be self.self represents the instance of the class, i.e., the address of the current instance object, not the class itself.self is not a reserved word in Python; it can be replaced with any variable name that follows the variable naming rules.3. Creating Objects (Instantiation) and Calling Attributes and MethodsInstances are created using the class name (with parameters), and instance objects are used to call attributes and methods within the class.
# Define the Car classclass Car:# Class attributes: color="black" wheel=4# Class method (private function of the class) def drive(self): print("Driving...")# Instantiate the classcar1=Car() # Instance object of the Car classcar2=Car() # Call object's attributes and methodsprint(car1.color) # The color attribute of car1 is blackcar2.drive() # Output: Driving...
4. Constructor:The constructor method of a class is __init__ (with two underscores before and after), used to initialize object attributes when creating an instance of the class. It is automatically called after the instance is created.Characteristics:(1) Fixed naming: The method name must be __init__, and the first parameter is always self (representing the instance being created, used to access instance attributes and methods).(2) Automatically executed: When creating an instance using the class name (()), __init__ is automatically triggered, requiring no manual call.(3) Flexible parameters: Besides self, any number of parameters can be defined to meet different initialization needs.(4) No return value: __init__ does not allow returning any value (including None), otherwise an exception will be raised.
class Person: # Define constructor method, initialize name and age def __init__(self,name,age): self.name=name self.age=age # Custom instance method def introduce(self): print(f"My name is {self.name}, I am {self.age} years old.")# Create instance: call constructor method, pass parametersperson1=Person("Zhang San",20)# Access instance attributes or call methodsprint(person1.name) # Output: Zhang Sanperson1.introduce() # Output: My name is Zhang San, I am 20 years old.
Note: The first parameter of the __init__() method is always self, representing the instance itself. Therefore, various attributes can be bound to self within the __init__() method.With the __init__() method, instances cannot be created with empty parameters; parameters matching those in the __init__() method must be passed, but self does not need to be passed, as the Python interpreter will automatically pass the instance variable.5. Class InheritanceInheritance in Python classes means that one class (subclass/derived class) can inherit attributes and methods from another class (parent class/base class), while the subclass can also add or override attributes and methods, achieving code reuse and extension.
# Define parent class (base class)class Animal: # Parent class constructor method def __init__(self, name): self.name = name # Parent class attribute # Parent class method def make_sound(self): print(f"{self.name} makes a sound")# Define subclass (derived class), inheriting from Animalclass Dog(Animal): # Override parent class constructor method (if new subclass attributes are needed) def __init__(self, name, breed): # Call parent class constructor method, initialize parent class attributes super().__init__(name) self.breed = breed # New attribute in subclass # Override parent class's make_sound method def make_sound(self): print(f"{self.name} ({self.breed}) barks")# 3. Create instance using subclassmy_dog = Dog("Wangcai", "Chinese Rural Dog")print(my_dog.name) # Inherit parent class attribute, output: Wangcaiprint(my_dog.breed) # New attribute in subclass, output: Chinese Rural Dogmy_dog.make_sound() # Call overridden method, output: Wangcai (Chinese Rural Dog) barks