【发布时间】:2020-01-04 02:47:39
【问题描述】:
考虑这段代码:
class testobj( object ): ...
x = testobj()
x.toast = 'toast'
print( x.toast ) # <-- toast
y = object()
y.toast = 'toast'
最后一行产生错误
AttributeError Traceback (most recent call last)
<ipython-input-24-873470c47cb3> in <module>()
----> 1 y.toast = 'toast'
AttributeError: 'object' object has no attribute 'toast'
我也试过
class testobj2( object ):
def __init__( self ):
super().__init__()
其行为方式相同,允许设置任意属性。
根据我对 Python 中继承的理解,我希望 testobj 与 object 具有所有相同的行为(所有相同的方法,包括 __setattr__),因为它是一个子类并且没有定义新方法.但是,它不一样,因为上面的代码允许我设置任意属性。为什么会发生这种情况?如何禁止设置任意属性?
【问题讨论】:
-
什么是toast(来自
y.toast = toast)? -
您看到的错误与您所描述的无关。如果改成
y.toast = "toast",错误就变成object object has no attribute toast,这就是问题所在。 -
对不起,这应该是一个字符串。
-
对象不会影响动态创建的属性。不管它们是如何相关的(除非你做了一些元魔法)。
-
@BaileyKocin 无意分享任何内容。他只是为两个对象添加了一个新属性。当类为
testobj时允许,当类为object时不允许。
标签: python inheritance