为什么 python super() 在 ABCMETA class 中没有参数就不能工作?
Why python super() not working without parameters in ABCMETA class?
我无法理解 abc.ABCMeta class 中 python3.6.
中的函数 super() 行为
class ParentClass():
def test():
return 1
@six.add_metaclass(ABCMeta)
class ChildClass(ParentClass):
def test(self):
test_ = super().test
test_ = 2
return test_
a = ChildClass()
a.test()
代码失败 'TypeError: super(type, obj): obj must be an instance or subtype of type'
。
当我使用 super(ChildClass, self).test
时它工作正常!从 ChildClass 测试函数打印:
print(__class__)
print(type(__class__))
print(ChildClass)
print(type(ChildClass))
我得到下一个输出:
<class '__main__.ChildClass'>
<class 'type'>
<class '__main__.ChildClass'>
<class 'abc.ABCMeta'>
我觉得是对象初始化的原因,但我无法以我目前的 OOP 和 Python OOP 技能理解这些信息。
0 参数 super
使用调用实际出现的 class,但在 @six.add_metaclass(ABCMeta)
之后,class 绑定到 ChildClass
名称是由装饰器创建的新 class。 0-argument super
仍然使用原来的 class.
如果您要使用仅适用于 Python 3 的 0 参数 super
,只需使用 Python 3 metaclass 语法而不是 six
.
我无法理解 abc.ABCMeta class 中 python3.6.
中的函数 super() 行为class ParentClass():
def test():
return 1
@six.add_metaclass(ABCMeta)
class ChildClass(ParentClass):
def test(self):
test_ = super().test
test_ = 2
return test_
a = ChildClass()
a.test()
代码失败 'TypeError: super(type, obj): obj must be an instance or subtype of type'
。
当我使用 super(ChildClass, self).test
时它工作正常!从 ChildClass 测试函数打印:
print(__class__)
print(type(__class__))
print(ChildClass)
print(type(ChildClass))
我得到下一个输出:
<class '__main__.ChildClass'>
<class 'type'>
<class '__main__.ChildClass'>
<class 'abc.ABCMeta'>
我觉得是对象初始化的原因,但我无法以我目前的 OOP 和 Python OOP 技能理解这些信息。
0 参数 super
使用调用实际出现的 class,但在 @six.add_metaclass(ABCMeta)
之后,class 绑定到 ChildClass
名称是由装饰器创建的新 class。 0-argument super
仍然使用原来的 class.
如果您要使用仅适用于 Python 3 的 0 参数 super
,只需使用 Python 3 metaclass 语法而不是 six
.