Python3 is object-oriented


May 10, 2021 03:00 Python3


Table of contents


Python has been an object-oriented language since its inception, which is why it is easy to create a class and object in Python. In this section we'll cover Python's object-oriented programming in more detail.

If you haven't been exposed to object-oriented programming languages before, you might want to understand some of the basic characteristics of object-oriented languages and develop a basic object-oriented concept in your head that will make it easier for you to learn Python's object-oriented programming.

Let's start with a simple look at some of the basic features of object-oriented.


Introduction to Python3 object-oriented technology

  • Class: A collection of objects that describe objects that have the same properties and methods. I t defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
  • Class variables: Class variables are common throughout the instantiated object. C lass variables are defined in the class and outside the function body. Class variables are not typically used as instance variables.
  • Data members: Class variables or instance variables are used to process related data for classes and their instance objects.
  • Method override: If the method inherited from the parent class does not meet the needs of the child class, you can override it, a process called override, also known as method override.
  • Local variable: A class that defines a variable in a method and only affects the current instance.
  • Instance variable: In the declaration of a class, properties are represented by variables. This variable, called an instance variable, is declared inside the class declaration but outside the other member methods of the class.
  • Inheritance: That is, a derived class inherits the fields and methods of the base class. I nheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where a Dog-type object is derived from the Animal class, which simulates an "is-a" relationship (for example, Dog is an Animal).
  • Instantiation: Creates an instance of a class, the specific object of the class.
  • Method: A function defined in a class.
  • Object: An instance of a data structure defined by a class. The object consists of two data members (class and instance variables) and methods.

Compared to other programming languages, Python adds class mechanisms without adding new syntax and semantics as much as possible.

Classes in Python provide all the basic functionality of object-oriented programming: the inheritance mechanism of the class allows for multiple base classes, and derived classes can override any method in the base class, in which the method of the same name can be called.

An object 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, and in effect, after a class is created, its properties can be accessed through the class name.

Class object

Class objects support two types of operations: property reference and instantiation.

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

Once a class object is created, all names in the class namespace are valid property names. So if the class definition is 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())

Instantiation class:

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

A new class instance is created above and the object is assigned to the local variable x, which is empty.

The output of the above program is:

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

Many classes tend to create objects as having an initial state. Therefore, a class might define a special __init__ (construct method) called "() as:

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

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

x = MyClass()

Of course, __init__ () method can have parameters that are passed through __init__() to the instantiation operation of the class. 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)

The method of the class

Inside the class, the def keyword can be used to define a method for the class, which, unlike a general function definition, must contain the argument self and be the first argument:

#!/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('W3Cschool',10,30)
p.speak()

The output of the above program is:

W3Cschool 说:  10 岁。

Inherited

Python also supports class inheritance, which makes little sense if a language does not support inheritance. The definition of a derived class is as follows:

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

Note the order of the base classes in parentheses, and if the base class has the same method name and is not specified when the sub-class is used, Python searches from left to right for whether the method contains methods in the base class when the method is not found in the sub-class.

BaseClassName (the base class name in the example) must be defined within a scope with the derived class. In addition to classes, you can also use expressions, which are useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName):

Instance

#!/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 of the above program is:

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

Multi-inheritance

Python also has limited support for multi-inheritance forms. Multi-inherited classes are defined as follows:

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

Note the order of the parent classes in parentheses, and if the parent class has the same method name and is not specified when the child class is used, Python searches from left to right, that is, if the method is not found in the child class, from left to right to find out 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 of the above program is:

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

Method override

If the functionality of your parent class method does not meet your needs, you can override your parent method in a child class, as follows:

#!/usr/bin/python3

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

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

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

The output of the above program is:

调用子类方法

Class properties and methods

The private property of the class

__private_attrs: Two underscores begin with a declaration that the property is private and cannot be used or accessed directly outside the class. When used in methods inside a class self.__private_attrs.

The method of the class

Inside the class, the def keyword can be used to define a method for the class, which, unlike a general function definition, must contain the argument self and be the first argument

The private method of the class

__private_method: Two underlined beginnings that declare the method private and cannot be called outside the class. The internal call to the slef.__private_methods.

Here's an example:

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

Proprietary methods of the class:

  • __init__: Constructor, called when the object is generated
  • __del__ : a destructor that is used when releasing an object
  • __repr__: Print, convert
  • __setitem__: Assign values by index
  • __getitem__: Get the value by index
  • __len__: Gets the length
  • __cmp__: Comparison operations
  • __call__: Function call
  • __add__: Plus operation
  • __sub__: Subtract
  • __mul__: Multiply
  • __div__: Divide operation
  • __mod__: The residual operation
  • __pow__: Multiplier

The operator is overloaded

Python also supports operator overloading, so can I overload the proprietary methods of the class, 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 above code execution results are as follows:

Vector(7,8)