super的使用
Posted weidaijie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了super的使用相关的知识,希望对你有一定的参考价值。
python3中使用super().__init__() #等同于super(C,self).__init__() 调用父类的初始化方法
class A(object): def __init__(self): print(‘i am class A‘) class C(A): def __init__(self,): super().__init__() #等同于super(C,self).__init__() print(‘yes‘) c = C() print(c.__class__) print(C.__bases__) i am class A yes <class ‘__main__.C‘> (<class ‘__main__.A‘>,)
class A(object): def __init__(self,name,age,hobby): self.name = name self.age = age self.hobby = hobby print(‘i am class A‘) class C(A): def __init__(self,name,age,hobby): super().__init__(name,age,hobby) #等同于super(C,self).__init__() print(‘yes‘) c = C("egon",18,"吃饭") print(c.name) print(c.__class__) print(C.__bases__)
调用父类的方法:
class A(object): def __init__(self,name,age,hobby): self.name = name self.age = age self.hobby = hobby print(‘i am class A‘) def eat(self): print("吃苹果") class C(A): def __init__(self,name,age,hobby): super().__init__(name,age,hobby) #等同于super(C,self).__init__() print(‘yes‘) def eat(self): print("吃梨") c = C("egon",18,"吃饭") c.eat() A.eat(c)#调用父类的方法 print(c.__class__) print(C.__bases__)
以上是关于super的使用的主要内容,如果未能解决你的问题,请参考以下文章