(100 days, 2 hours, fourth day) class inheritance

1. The new class created by inheritance is called a subclass or derived class , and the inherited class is called a base class , a parent class or a super class .

Some features of inheritance in python:

  • 1. If you need the construction method of the parent class in the subclass, you need to explicitly call the construction method of the parent class, or do not override the construction method of the parent class.
  • 2. When calling the method of the base class, you need to add the class name prefix of the base class, and you need to bring the self parameter variable. The difference is that the self parameter is not required when calling ordinary functions in the class
  • 3. Python always looks for the method of the corresponding type first. If it can't find the corresponding method in the derived class, it starts to search one by one in the base class. (First find the called method in this class, and then go to the parent class if you can't find it).

If more than one class is listed in the inheritance tuple, then it is called "multiple inheritance".

class Parent:        # 定义父类
    parentAttr = 100
    def __init__(self):
        print("调用父类构造函数")

    def parentMethod(self):
        print('调用父类方法')

    def setAttr(self, attr):
        Parent.parentAttr = attr

    def getAttr(self):
        print("父类属性 :", Parent.parentAttr)

class Child(Parent): # 定义子类
    def __init__(self):
        print("调用子类构造方法")

    def childMethod(self):
        print('调用子类方法')

c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值

2. 1.issubclass()-Boolean function to determine whether a class is a subclass or descendant class of another class, syntax: issubclass(sub,sup)

  Note: Add parentheses when instantiating an object.

class A:
    def __init__(self):
        print("math")
class B:
    def __init__(self):
        print("hello")
class C(A,B):
    def __init__(self):
        print("world")

c=C()  #注意括号,要记得加括号,实例化时就会调用本身的方法
print(issubclass(C,A)) #判断C是不是A的子类
print(isinstance(c, C)) #判断c是不是C的实例化对象
print(isinstance(c, B)) #判断c是不是B的实例化对象或者B的子孙类的实例化对象

  

2. isinstance(obj, Class) Boolean function returns true if obj is an instance object of Class class or an instance object of a Class subclass.

class Parent:        # 定义父类
    parentAttr = 100
    def __init__(self):
        print("调用父类构造函数")

class Child(Parent): # 定义子类
    def __init__(self):
        print("调用子类构造方法")

c = Child()          # 实例化子类,实例化时就会有输出

print(isinstance(c, Child))

 

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109366074