13, advanced object-oriented

1. Inheritance of objects

 A class can inherit one parent class or multiple parent classes. Among them, the former is called single inheritance, and the latter is called multiple inheritance.

Single inheritance: class subclass name (parent class)
multiple inheritance: class subclass name (parent class 1, parent class 2, ...)

Example 1: Complete inheritance

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
    def area(self):
        return self.length*self.width
        
class Square(Rectangle):
     pass
squ=Square(6,6)
print(squ.area())

Execution result: 36

Example 2: Partial inheritance, no method modification

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
        
    def area(self):
        return self.length*self.width
        
class Square(Rectangle):
     def __init__(self,side):   #只对初始化方法进行修改
        self.length=side
        self.width=side
squ=Square(6)
print(squ.area())

Implementation results: 36


Example 3: Partial inheritance, while inheriting the method and adding

class Rectangle:
    def __init__(self,length,width):
        self.length=length
        self.width=width
        
    def area(self):
        return self.length*self.width
        
    @classmethod
    def features(cls):
        print('父类的类方法')
        
class Square(Rectangle):
    def __init__(self,side):
        self.length=side
        self.width=side
    @classmethod
    def features(cls):
        super().features()    # 继承父类的同名方法的代码
        print('子类的类方法')  # 补充
squ=Square(6)
squ.features()

Results of the:

父类的类方法
子类的类方法


Example 4: Multiple inheritance

class people:
    def __init__(self,n,a):   #构造方法
        self.name = n  
        self.__age = a       
    def speak(self,height):     #实例方法,其中height为实例属性
        print("%s 说: 我 %d 岁,身高 %d cm。" %(self.name,self.age,height))

class speaker():
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多重继承
class sample(speaker,people):
    def __init__(self,n,a,t):
        people.__init__(self,n,a)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,"Python")
test.speak()   #方法名同,默认调用的是在括号中排较前父类的方法

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

Note: If there is the same method name in the parent class, but it is not specified when the subclass is used, python searches from left to right in the parent class

2. Distinguish between static methods and class methods:

Method 1: type() method,
static method returns function, class method returns method

class people:           
    @classmethod  #声明下面是个类方法
    def f1(cls):
        print('这是类方法')

    @staticmethod  #声明下面是个静态方法
    def f2():
        print('这是静态方法')
        
print(type(people.f1))
print(type(people.f2))

Results of the:

<class 'method'>
<class 'function'>

Method 2: inspect() function
can be judged by inspect.ismethod() and inspect.isfunction()

#追加代码
import inspect
print(inspect.ismethod(people.f1))
print(inspect.isfunction(people.f2))

Results of the:

True
True

3. Private attributes, private methods

  • Private attributes: attributes that cannot be inherited by subclasses
  • Private methods: methods that cannot be inherited by subclasses
  • Format: Add "__" before the attribute/method, it becomes private

① Call private directly:

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')

a=A()
print(a.__name)  #调用私有属性
a.__f1()    #调用私有方法

Execution result: error

AttributeError: 'A' object has no attribute '__name'
AttributeError: 'A' object has no attribute '__f1'

Summary: directly call private properties, private methods report errors

② call private through inheritance:

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')

class B(A):
    pass
b=B()
print(b.__name)
b.__f1()

Execution result: error

AttributeError: 'B' object has no attribute '__name'
AttributeError: 'B' object has no attribute '__f1'


③ Indirect call

class A:
    __name='private'  #私有属性
    def __init__(self):
        pass
    def __f1(self):  #私有方法
        print('这是一个私有方法')
    def f2(self):
        print(self.__name)
        self.__f1()

a=A()
a.f2()

Results of the:

private
这是一个私有方法

4. Object class

All classes are subclasses of object

class A:
    """A的注释"""
class B(object):
    """B的注释"""

print(A.__bases__)  #查看A的父类
print(A.__doc__)  #查看A的注释
print(A.__name__)  #查看A的类名
print(B.__bases__)
print(B.__doc__)

Results of the

(<class 'object'>,)
A的注释
A
(<class 'object'>,)
B的注释

5. Polymorphism

class A():
    def f1(self):
        print('A的f1')
class B():
    def f1(self):
        print('B的f1')
        
def f(obj):  
    obj.f1()

f(A())  
f(B())  

Results of the:

A的f1
B的f1

Guess you like

Origin blog.csdn.net/weixin_45128456/article/details/112188096