Example Analysis of python Class Inheritance Chain

  • 2021-11-02 01:28:01
  • OfStack

1. The child class can inherit the parent class. Similarly, the parent class can inherit its own parent class, layer by layer.


class A:
def have(self):
print('I hava an apple')
 
class B(A):
pass
 
class C(B):
pass

2. If you want to determine whether one category is a subcategory of another category, you can use the built-in function issubclass ().


>>> issubclass(C, A)
True
>>> issubclass(B, A)
True
>>> issubclass(C, B)
True

Extension of knowledge points:

Definition of inheritance


class Person(object):   #  Definition 1 Parent class 
 
    def talk(self):    #  Methods in the parent class 
        print("person is talking....")  
 
 
class Chinese(Person):    #  Definition 1 Subclass,   Inheritance Person Class 
 
    def walk(self):      #  Define its own methods in subclasses 
        print('is walking...')
 
c = Chinese()
c.talk()      #  Invoke the inherited Person Methods of the class 
c.walk()     #  Invoke its own method 
 
#  Output 
 
person is talking....
is walking...

Inheritance of constructor


class Person(object):
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.weight = 'weight'
 
    def talk(self):
        print("person is talking....")
 
 
class Chinese(Person):
 
    def __init__(self, name, age, language):  #  Inherit first, reconstruct 
        Person.__init__(self, name, age)  # Inherit the constructor of the parent class, and can also be written as: super(Chinese,self).__init__(name,age)
        self.language = language    #  Define the properties of the class itself 
 
    def walk(self):
        print('is walking...')
 
 
class American(Person):
    pass
 
c = Chinese('bigberg', 22, 'Chinese')

Related articles: