Subclass calls method of parent class in Python

If you want to call the method of the parent class in the subclass, you can use the class name to call it directly. At this time, the self parameter cannot be omitted.

class Animal:
    def __init__(self,name,age,weight):
        self.name=name
        self.age=age
        self.weight=weight
class Dog(Animal):
    def __init__(self,name,age,weight,owner):
        Animal .__ init__ (self,name,age ,weight) #Note that Animal(name,age,weight) cannot be used here 
        self.owner= owner

d1 =Dog( ' Xiaobai ' , ' 2 ' , ' 20 ' , ' Xiaohei ' )
 print ( ' %s' owner is %s ' %(d1.name,d1.owner)) #Xiaobai's owner is little black

Although the above method can achieve basic functions, the scalability is relatively poor. Because when the parent class name is modified, the following must be modified. At this time, you can use the super() method to solve this problem.

class Animal:
    def __init__(self,name,age,weight):
        self.name=name
        self.age=age
        self.weight=weight
class Dog(Animal):
    def __init__(self,name,age,weight,owner):
        super().__init__(name,age,weight)
        self.owner=owner

d1 =Dog( ' Xiaobai ' , ' 2 ' , ' 20 ' , ' Xiaohei ' )
 print ( ' %s' owner is %s ' %(d1.name,d1.owner))#Xiaobai's owner is little black

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326605254&siteId=291194637