1.直接写类名调用: parent_class.parent_attribute(self)
1 class Animal(): 2 3 def __init__(self, name): 4 self.name = name 5 6 def say_name(self): 7 print(self.name) 8 9 10 class Dog(Animal): 11 12 def __init__(self, name): 13 Animal.__init__(self, name) 14 15 def say_name(self): 16 Animal.say_name(self) 17 18 19 dog = Dog(‘小虎‘) 20 dog.say_name() # 打印‘小虎‘
扩展:实例对象和类对象调用实例函数。
1 class Animal(): 2 3 def __init__(self, name): 4 self.name = name 5 6 def say_name(self): 7 print(self.name) 8 9 animal = Animal(‘nada‘) 10 animal.say_name() # 实例对象调用实例函数,输出‘nada‘ 11 Animal.say_name(animal) # 类对象调用实例函数,需要传入一个对象实例作为参数,输出‘nada‘
2.用 super(type, obj).method(arg)方法调用:super(child_class, child_object).parent_attribute(arg) 【不需要写self】
1 class Animal(object): 2 3 def __init__(self, name): 4 super(Animal, self).__init__() 5 self.name = name 6 7 def say_name(self): 8 print(self.name) 9 10 11 class Dog(Animal): 12 13 def __init__(self, name): 14 super(Dog, self).__init__(name) 15 16 def say_name(self): 17 super(Dog, self).say_name() 18 19 20 dog = Dog(‘小虎‘) 21 dog.say_name() # 输出‘小虎‘