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

时间:2019-01-23 15:14:35

标签: python class oop inheritance super

如果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

0 个答案:

没有答案