One of the main benefits of object-oriented programming is the reuse of code. One of the ways to achieve this reuse is through the inheritance of the Python class and on this basis, Python is derived Inherit methods from multiple classes.
The new class created through the inheritance of Python class is called subclass or derived class, and the inherited class is called Base class , parent class or superclass.
Inheritance syntax:
class 派生类名(基类名) ...
Example
#!/usr/bin/python # -*- coding: UTF-8 -*- 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() # 再次调用父类的方法 - 获取属性值
The above code execution results are as follows:
调用子类构造方法 调用子类方法 调用父类方法 父类属性 : 200
Inheritance of classes Extension: Python inherits multiple classes
class A: # 定义类 A ..... class B: # 定义类 B ..... class C(A, B): # 继承类 A 和 B .....
You can use the issubclass() or isinstance() method to detect.
issubclass() - Boolean function determines whether a class is a subclass or descendant of another class. Syntax: issubclass(sub,sup)
isinstance(obj, Class) Boolean function if obj Returns true if it is an instance object of the Class class or an instance object of a Class subclass.
The above is the detailed content of How to make Python inherit from multiple classes? Understand the inheritance of Python classes in one article. For more information, please follow other related articles on the PHP Chinese website!