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:

class ClassName: <statement-1> . . . <statement-N>

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+)

#!/usr/bin/python3 class MyClass: """A simple class example""" i = 12345 def f(self): return 'hello world' # Instantiate the class x = MyClass() # Access the class's attributes and methods print("The attribute i of the MyClass class is:", x.i) print("The method f of the MyClass class outputs:", x.f())

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:

def __init__(self): self.data = []

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+)

#!/usr/bin/python3 class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r, x.i) # Output result: 3.0 -4.5

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.

class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt()

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:

class Test: def prt(example): print(example) print(example.__class__) t = Test() t.prt()

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

class MyClass:
    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+)

#!/usr/bin/python3 # Class definition class people: # Define basic attributes name = '' age = 0 # Define private attributes. Private attributes cannot be directly accessed outside the class. __weight = 0 # Define the constructor method def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s says: I am %d years old." %(self.name,self.age)) # Instantiate the class p = people('example',10,30) p.speak()

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:

class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>

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+)

#!/usr/bin/python3 # Class definition class people: # Define basic attributes name = '' age = 0 # Define private attributes. Private attributes cannot be directly accessed outside the class. __weight = 0 # Define the constructor method def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s says: I am %d years old." %(self.name,self.age)) # Single inheritance example class student(people): grade = '' def __init__(self,n,a,w,g): # Call the parent class constructor people.__init__(self,n,a,w) self.grade = g # Override the parent class method def speak(self): print("%s says: I am %d years old, and I am in grade %d"%(self.name,self.age,self.grade)) s = student('ken',10,60,3) s.speak()

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:

class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>

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+)

#!/usr/bin/python3 # Class definition class people: # Define basic attributes name = '' age = 0 # Define private attributes; private attributes cannot be directly accessed outside the class __weight = 0 # Define the constructor method def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s says: I am %d years old." %(self.name,self.age)) # Single inheritance example class student(people): grade = '' def __init__(self,n,a,w,g): # Call the parent class constructor people.__init__(self,n,a,w) self.grade = g # Override the parent class method def speak(self): print("%s says: I am %d years old, and I am in grade %d"%(self.name,self.age,self.grade)) # Another class, preparation before multiple inheritance class speaker(): topic = '' name = '' def __init__(self,n,t): self.name = n self.topic = t def speak(self): print("My name is %s, I am a speaker, and my speech topic is %s"%(self.name,self.topic)) # Multiple inheritance class sample(speaker,student): a ='' def __init__(self,n,a,w,g,t): student.__init__(self,n,a,w,g) speaker.__init__(self,n,t) test = sample("Tim",25,80,4,"Python") test.speak() # If method names are the same, the method of the parent class with the earlier position in the parentheses is called by default

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+)

#!/usr/bin/python3 class Parent: # Define the parent class def myMethod(self): print ('Call the parent class method') class Child(Parent): # Define the subclass def myMethod(self): print ('Call the subclass method') c = Child() # Subclass instance c.myMethod() # The subclass calls the overridden method super(Child,c).myMethod() # Use a subclass object to call the parent class method that was overridden

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+)

#!/usr/bin/python3 class JustCounter: __secretCount = 0 # Private variable publicCount = 0 # Public variable def count(self): self.__secretCount += 1 self.publicCount += 1 print (self.__secretCount) counter = JustCounter() counter.count() counter.count() print (counter.publicCount) print (counter.__secretCount) # Error: the instance cannot access the private variable

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+)

#!/usr/bin/python3 class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # Private method print('This is a private method') def foo(self): # Public method print('This is a public method') self.__foo() x = Site('Example', 'www.example.com') x.who() # Normal output x.foo() # Normal output x.__foo() # Error

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+)

#!/usr/bin/python3 class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print (v1 + v2)

The execution result of the above code is as follows:

Vector(7,8)
Other extensions