gpt4 book ai didi

python - 覆盖 __init__ 时属性不可用?

转载 作者:行者123 更新时间:2023-11-28 20:29:54 25 4
gpt4 key购买 nike

我正在尝试覆盖 __init__ 方法,但是当我调用 super 方法时,在该方法中创建的属性不可用。我可以看出这不是继承问题,因为 class B 仍然具有可用的属性。

我认为代码示例会更好地解释它:-)

Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def __init__(self, *args, **kwargs):
... self.args = args
... self.kwargs = kwargs
...
>>> a = A('a', 'b', key='value')
>>> print a.args, a.kwargs
('a', 'b') {'key': 'value'}
>>> class B(A):
... pass
...
>>> b = B('b', 'c', key_b='value_b')
>>> print b.args, b.kwargs
('b', 'c') {'key_b': 'value_b'}
>>> class C(A):
... def __init__(self, *args, **kwargs):
... print 'class C'
... super(A, self).__init__(*args, **kwargs)
...
>>> c = C('c', 'd', key_c='value_C')
class C
>>> print c.args, c.kwargs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'args'
>>> class D(A):
... def __init__(self, *args, **kwargs):
... super(A, self).__init__(*args, **kwargs)
... print 'D'
...
>>> d = D('d', 'e', key_d='value D')
D
>>> print d.args, d.kwargs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'args'
>>>

最佳答案

您对父类(super class)的调用需要使用它自己的类型

super(D, self).__init__(*args,**kwargs)

而不是

super(A...

我相信调用 super(A, self).__init__ 将调用 A 的父类(super class),即 object。相反,您想调用 D 的父类(super class),即 A

关于python - 覆盖 __init__ 时属性不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/767241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com