Python3 Object-Oriented
Python has been an object-oriented language from the very beginning of its design. Because of this, it is very easy to create classes and objects in Python. This chapter will introduce Python's object-oriented programming in detail.
If you have not been exposed to object-oriented programming languages before, you may need to first understand some basic features of object-oriented languages and form a basic concept of object orientation in your mind, which will help you learn Python's object-oriented programming more easily.
Next, let's briefly understand some basic features of object orientation.
Introduction to Object-Oriented Technology
- Class:Used to describe a collection of objects with the same attributes and methods. It defines the attributes and methods common to each object in the collection. An object is an instance of a class.
- Method:A function defined in a class.
- Class variable:A class variable is shared among all instantiated objects. Class variables are defined in the class and outside any function body. Class variables are usually not used as instance variables.
- Data members:Class variables or instance variables are used to process data related to the class and its instance objects.
- Method overriding:If a method inherited from the parent class cannot satisfy the needs of the subclass, it can be rewritten. This process is called method override.
- Local variable:A variable defined in a method, which only affects the class of the current instance.
- Instance variable:In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self.
- Inheritance:That is, a derived class inherits the fields and methods of a base class. Inheritance also allows an object of a derived class to be treated as an object of the base class. For example, there is such a design: an object of type Dog derived from the Animal class, which simulates an "is-a" relationship (for example, Dog is an Animal).
- Instantiation:Creating an instance of a class, the concrete object of the class.
- Object:An instance of a data structure defined by a class. Objects include two data members (class variables and instance variables) and methods.
Compared with other programming languages, Python added the class mechanism without adding new syntax and semantics as much as possible.
Classes in Python provide all the basic functions of object-oriented programming: the class inheritance mechanism allows multiple base classes, derived classes can override any method in the base class, and methods can call methods with the same name in the base class.
Objects can contain any number and type of data.
Class Definition
The syntax format is as follows:
After a class is instantiated, its attributes can be used. In fact, after creating a class, its attributes can be accessed through the class name.
Class Objects
Class objects support two operations: attribute reference and instantiation.
Attribute references use the same standard syntax as all attribute references in Python:obj.name。
After a class object is created, all names in the class namespace are valid attribute names. So if the class definition is like this:
Examples (Python 3.0+)
The above created a new class instance and assigned the object to a local variable x, where x is an empty object.
The output of executing the above program is:
MyClass 类的属性 i 为: 12345 MyClass 类的方法 f 输出为: hello world
The class has a special method named __init__() (constructor method), which is automatically called when the class is instantiated, like this:
If a class defines the __init__() method, the class instantiation operation will automatically call the __init__() method. As shown below, when instantiating the class MyClass, the corresponding __init__() method will be called:
x = MyClass()
Of course, the __init__() method can have parameters, and parameters are passed through __init__() to the class instantiation operation. For example:
Examples (Python 3.0+)
self represents the instance of the class, not the class
The only special difference between class methods and ordinary functions is that they must have an additionalfirst parameter name, which by convention is named self.
The execution result of the above example is:
<__main__.Test instance at 0x100771878> __main__.Test
It can be clearly seen from the execution result that self represents the instance of the class, representing the address of the current object, while self.class points to the class.
self is not a Python keyword. If we change it to example, it will still execute normally:
The execution result of the above example is:
<__main__.Test instance at 0x100771878> __main__.Test
In Python, self is a conventional name used to represent the instance (object) of a class itself. It is a reference to the instance, allowing the class's methods to access and manipulate the instance's attributes.
When you define a class and define methods in the class, the first parameter is usually named self. Although you can use other names, it is strongly recommended to use self to maintain code consistency and readability.
Example
def __init__(self, value):
self.value = value
def display_value(self):
print(self.value)
# Create an instance of a class
obj = MyClass(42)
# Call a method of the instance
obj.display_value() # Output 42
In the above example, self is a reference pointing to the class instance. It is used in the__init__constructor to initialize the instance's attributes, and also indisplay_valuemethods to access the instance's attributes. By using self, you can access and manipulate the instance's attributes in the class's methods, thereby implementing the class's behavior.
Class Methods
Inside the class, use thedefkeyword to define a method. Unlike general function definitions, class methods must include the parameter self, and it must be the first parameter. self represents the instance of the class.
Examples (Python 3.0+)
The output of executing the above program is:
example 说: 我 10 岁。
Inheritance
Python also supports class inheritance. If a language does not support inheritance, classes are meaningless. The definition of a derived class is as follows:
A subclass (derived class DerivedClassName) will inherit the attributes and methods of the parent class (base class BaseClassName).
BaseClassName (the base class name in the example) must be in the same scope as the derived class definition. In addition to classes, expressions can also be used. This is very useful when the base class is defined in another module:class DerivedClassName(modname.BaseClassName):
Examples (Python 3.0+)
The output of executing the above program is:
ken 说: 我 10 岁了,我在读 3 年级
Multiple Inheritance
Python also has limited support for multiple inheritance. The class definition for multiple inheritance is as follows:
Note the order of parent classes in parentheses. If the parent classes have a method with the same name and the subclass does not specify which one when using it, Python searches from left to right. That is, when the method is not found in the subclass, it checks the parent classes from left to right to see whether they contain the method.
Examples (Python 3.0+)
The output of the above program is:
我叫 Tim,我是一个演说家,我演讲的主题是 Python
Method Overriding
If a parent class method cannot meet your needs, you can override the parent class method in the subclass. Example:
Examples (Python 3.0+)
super() functionis used to call a method of the parent class (superclass).
The output of the above program is:
Call subclass method Call superclass method
More documentation:
Explanation of Python subclass inheriting the parent class constructor
Class Attributes and Methods
Private Attributes of a Class
__private_attrs: Starts with two underscores, declaring the attribute as private. It cannot be used or directly accessed outside the class. When used in methods inside the class...self.__private_attrs。
Class Methods
Inside a class, use the def keyword to define a method. Unlike ordinary function definitions, a class method must include a parameterself, and it must be the first parameter,selfrepresenting the instance of the class.
selfIts name is not fixed; you can also usethis, but it is best to follow the convention.self。
Private Methods of a Class
__private_method: Starts with two underscores, declaring the method as a private method. It can only be called inside the class, not outside the class.self.__private_methods。
Example
The following is an example of class private attributes:
Examples (Python 3.0+)
The output of the above program is:
1
2
2
Traceback (most recent call last):
File "test.py", line 16, in <module>
print (counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
The following is an example of class private methods:
Examples (Python 3.0+)
The execution result of the above example:

Special methods of a class:
- __init__ :Constructor, called when an object is created
- __del__ :Destructor, used when releasing an object
- __repr__ :Printing, conversion
- __setitem__ :Assignment by index
- __getitem__:Get value by index
- __len__:Get length
- __cmp__:Comparison operation
- __call__:Function call
- __add__:Addition operation
- __sub__:Subtraction operation
- __mul__:Multiplication operation
- __truediv__:Division operation
- __mod__:Modulo operation
- __pow__:Power
Operator Overloading
Python also supports operator overloading. We can overload the special methods of a class. Example:
Examples (Python 3.0+)
The execution result of the above code is as follows:
Vector(7,8)Other extensions