Python3 object-oriented


Python has been an object-oriented language from the beginning. Because of this, it is easy to create classes and objects in Python. In this chapter we will introduce object-oriented programming in Python 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 object-oriented concept in your mind, which will help you Easily learn object-oriented programming in Python.

Next, let’s briefly understand some basic characteristics of object-oriented.


Introduction to object-oriented technology

  • Class (Class): Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes.

  • Class variables: Class variables are public throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally 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 rewriting: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override (override ), also known as method overriding.

  • Instance variables: Variables defined in methods only act on the class of the current instance.

  • Inheritance: That is, a derived class (derived class) inherits the fields and methods of the base class (base class). Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).

  • Instantiation: Create an instance of a class, a specific object of the class.

  • Method: Function defined in the class.

  • Object: Instance of data structure defined by class. Objects include two data members (class variables and instance variables) and methods.

Compared with other programming languages, Python adds a 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 inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and the method can call the same name in the base class method.

Objects can contain any amount and type of data.

Class definition

The syntax format is as follows:

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

After a class is instantiated, its properties can be used. In fact, after a class is created, its properties can be accessed through the class name. .

Class object

Class object supports two operations: attribute reference and instantiation.

Attribute references use the same standard syntax as all property references in Python: obj.name.

After the class object is created, all names in the class namespace are valid attribute names. So if the class definition is like this:

#!/usr/bin/python3

class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'

# 实例化类
x = MyClass()

# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())

Instantiate the class:

# 实例化类
x = MyClass()
# 访问类的属性和方法

The above creates a new class instance and assigns the object to the local variable x, x is an empty object.

The output result of executing the above program is:

MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world

Many classes tend to create objects with an initial state. Therefore, the class may define a special method (constructor) named __init__(), like the following:

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

If the class defines the __init__() method, the instantiation operation of the class will automatically call_ _init__() method. So in the following example, you can create a new instance like this:

x = MyClass()

Of course, the __init__() method can have parameters, and the parameters are passed to the instantiation operation of the class through __init__(). For example:

>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

Method of class

Within the class, you can use the def keyword to define a method for the class. Different from the general function definition, the class method must contain the parameter self, and it is the first parameter. One parameter:

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

# 实例化类
p = people('php',10,30)
p.speak()

The output result of executing the above program is:

php 说: 我 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(BaseClassName1):
    <statement-1>
    .
    .
    .
    <statement-N>

You need to pay attention to the order of the base class in the parentheses. If there is the same method name in the base class, but it is not specified when using the subclass, Python will search from left to right. That is, when the method is not found in the subclass, it searches from left to right to see if the method is included in the base class.


#BaseClassName (the base class name in the example) must be defined in the same scope as the derived class. In addition to classes, expressions can also be used, which is very useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Example

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))



s = student('ken',10,60,3)
s.speak()

The output result of executing the above program is:

ken 说: 我 10 岁了,我在读 3 年级

Multiple inheritance

Python also has limited support for multiple inheritance forms. The class definition of multiple inheritance looks like the following example:

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

You need to pay attention to the order of the parent class in the parentheses. If there is the same method name in the parent class and it is not specified when using it in the subclass, Python goes from left to right. search That is, when the method is not found in the subclass, search from left to right to see if the parent class contains the method.

#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))

#另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))

#多重继承
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()   #方法名同,默认调用的是在括号中排前地父类的方法

The output result of executing the above program is:

我叫 Tim,我是一个演说家,我演讲的主题是 Python

Method rewriting

If the function of your parent class method cannot meet your needs, you can The subclass overrides the method of your parent class. The example is as follows:

#!/usr/bin/python3

class Parent:        # 定义父类
   def myMethod(self):
      print ('调用父类方法')

class Child(Parent): # 定义子类
   def myMethod(self):
      print ('调用子类方法')

c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法

The output result of executing the above program is:

调用子类方法

Class attributes and methods

Private of the class Attribute

__private_attrs: Starting with two underscores, it is declared that the attribute is private and cannot be used or directly accessed outside the class. When used in a method inside a class self.__private_attrs.

Methods of class

Within the class, you can use the def keyword to define a method for the class. Different from the general function definition, the class method must contain the parameter self, and it is the first parameter.

Private methods of the class

__private_method: Beginning with two underscores, it is declared that the method is a private method and cannot be called outside the class. Call slef.__private_methods inside the class.

The example is as follows:

#!/usr/bin/python3

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 报错,实例不能访问私有变量

The output result of executing 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'

Proprietary method of class:

  • __init__ : Constructor, called when creating an object

  • __del__ : Destructor, called when releasing an object

  • __repr__ : Print, convert

  • __setitem__ : Assign value according to index

  • __getitem__: Get the value according to the index

  • __len__: Get the length

  • __cmp__ : Comparison operation

  • __call__: Function call

  • __add__: Addition operation

  • __sub__: Subtraction operation

  • __mul__: Multiplication operation

  • __div__: Division operation

  • __mod__: Remainder operation

  • __pow__: Square expression

Operator overloading

Python also supports operator overloading. We can overload the proprietary methods of the class. The example is as follows:

#!/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)