(用Python shell编写)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> …
Run Code Online (Sandbox Code Playgroud) 我有这个代码:
>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
Run Code Online (Sandbox Code Playgroud)
这段代码:
>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
Run Code Online (Sandbox Code Playgroud)
根据我的Python知识,我会说datetime
覆盖setattr
/ getattr
,但我不确定.你能在这里说清楚吗?
编辑:我不是特别感兴趣datetime
.我总是想知道对象.
在python中,为这样的对象实例创建新属性是非法的
>>> a = object()
>>> a.hhh = 1
Run Code Online (Sandbox Code Playgroud)
投
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hhh'
Run Code Online (Sandbox Code Playgroud)
但是,对于一个函数对象,它是可以的.
>>> def f():
... return 1
...
>>> f.hhh = 1
Run Code Online (Sandbox Code Playgroud)
这种差异背后的理由是什么?