我试图了解何时以及如何正确使用Python中的super()(2.7.x或3.x)
在>>> help(super)口译员告诉我如何称呼它:
class super(object)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
Run Code Online (Sandbox Code Playgroud)
我明白在Python3.x中,现在可以在类定义中使用super(),但我不明白为什么super(obj)不可能.或者super(self)在类定义中.
我知道必须有理由,但我找不到它.对我来说,这些线条相当于super(obj.__class__, obj)或者super(self.__class__, self)那些可以正常工作吗?
我认为super(obj)即使在Python 3.x中输入也是一个很好的捷径.
我想知道Python 3中的新超级是如何实现的.
在我做了一个小例子之后,这个问题就出现在了我脑海中,我得到了一个奇怪的错误.我正在使用Pyutilib组件架构(PCA),我已经制作了自定义元类来驱动另一个类的创建:
from pyutilib.component.core import implements, SingletonPlugin, PluginMeta, Interface
class IPass(Interface):
pass
class __MetaPlugin(PluginMeta):
def __new__(cls, name, baseClasses, classdict):
print(cls, name, baseClasses, classdict)
if baseClasses:
baseClasses += (SingletonPlugin,)
return PluginMeta.__new__(cls, name, baseClasses, classdict)
class Pass(metaclass=__MetaPlugin):
implements(IPass)
def __init__(self, inputs=[], outputs=[]):
self.inputs = []
self.outputs = []
class A(Pass):
def __init__(self):
print(self.__class__) # <class '__main__.A'>
print(self.__class__.__class__) # <class '__main__.__MetaPlugin'>
print(PluginMeta.__class__) # <class 'type'>
super().__init__() # SystemError: super(): empty __class__ cell
#Pass.__init__(self) - this works
a = A()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误: …
python 中内置函数的一个用例super()是调用重写的方法。super()这是一个使用调用Parent类函数的简单示例echo:
class Parent():
def echo(self):
print("in Parent")
class Child(Parent):
def echo(self):
super().echo()
print("in Child")
Run Code Online (Sandbox Code Playgroud)
我见过将 2 个参数传递给super(). 在这种情况下,签名看起来有点像子类从super(subClass, instance)哪里调用,并且是调用的实例,即。因此,在上面的示例中,该行将变为:subClasssuper()instanceselfsuper()
super(Child, self).echo()
Run Code Online (Sandbox Code Playgroud)
查看python3 文档,从类内部调用时,这两个用例是相同的。
super()从 python3 开始,使用 2 个参数的调用是否已完全弃用?如果这仅在调用重写函数时被弃用,您能否举例说明为什么其他情况需要它们?
我也有兴趣知道为什么 python 需要这两个参数?在 python3 中进行调用时是否会注入/评估它们super(),或者在这种情况下不需要它们?