Details of the inheritance instance of the Python class

  • 2020-05-27 06:11:46
  • OfStack

Inheritance details for class Python

Since Python is object-oriented, it certainly supports class inheritance, while Python implements class inheritance more easily than JavaScript.

Parent class:


class Parent: 
 
  parentAttr = 100 
 
  def __init__(self): 
    print("parent Init") 
 
  def parentMethod(self): 
    print("parentMethod") 
   
  def setAttr(self,attr): 
    self.parentAttr = attr 
 
  def getAttr(self): 
    print("ParentAttr:",Parent.parentAttr) 

Child class


class Child(Parent): 
 
  def __init__(self): 
    print("child init") 
 
  def childMethod(self): 
    print("childMethod") 

call


p1 = Parent(); 
p1.parentMethod(); 
 
c1 = Child(); 
c1.childMethod(); 

Output:


parent Init 
parentMethod 
child init 
childMethod 
Press any key to continue . . . 

Python supports multiple inheritance


class A:    #  Define the class  A 
..... 
 
class B:     #  Define the class  B 
..... 
 
class C(A, B):  #  A derived class  A  and  B 
..... 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: