如果我们可以用bass类的实例调用原始bass类函数,为什么我们会有一个超级函数?

2024-10-06 07:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我们需要使用super(drived_class, self)如果bass_class()可以做同样的工作,那么超级函数到底做什么呢? 我戴着一些密码试图找出答案,但没有得到很多。 什么是<super: <class 'b'>, <b object>>?它有什么理由把self作为第二个参数,不像其他函数

>>>class a(object):
...    def somefunc(self):
...        print("af function")
>>>class b(a):
...    def somefunc(self):
...        print("overriding af")
...    def recalling_bassclass_somefunc(self):
...        print("////")
...        print("recalling it via super func")
...        super(b,self).somefunc()
...        print("recalling it via super func with b() instead of self")
...        super(b,b()).somefunc()
...        print("recalling it via an a class object")
...        print(a().somefunc)
...        print("printing the a class")
...        print(a())
...        print("printing a type")
...        print(type(a()))
...        print("printing the super(b,self)")
...        print(super(b,self))
...        print("printing the super(b,self) type")
...        print(type(super(b,self)))
...        print(type(a()) == type(super(b,self)))
...        print(a() == super(b,self))
...a().somefunc()
...b().somefunc()
...b().recalling_bassclass_somefunc()
af function
overriding af
////
recalling it via super func
af function
recalling it via super func with b() instead of self
af function
recalling it via an a class object
<bound method a.somefunc of <__main__.a object at 0x00000201DCD207F0>>
printing the a class
<__main__.a object at 0x00000201DCCED748>
printing a type
<class '__main__.a'>
printing the super(b,self)
<super: <class 'b'>, <b object>>
printing the super(b,self) type
<class 'super'>
False
False

Tags: theselfobjecttypeitfunctionviaclass