为什么我不能直接向任何python对象添加属性?

时间:2009-03-08 12:46:57

标签: python attributes object

我有这段代码:

>>> class G:
...   def __init__(self):
...     self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000

这段代码:

>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'

根据我的Python知识,我会说datetime会覆盖setattr / getattr,但我不确定。你能在这里说清楚吗?

编辑:我对datetime并不特别感兴趣。我一直在想对象。

3 个答案:

答案 0 :(得分:32)

我的猜测是,datetime的实现使用__slots__来获得更好的性能。

使用__slots__时,解释器仅为列出的属性保留存储空间,而不保留其他内容。这样可以提供更好的性能并减少存储空间,但这也意味着您无法随意添加新属性。

在此处阅读更多内容:http://docs.python.org/reference/datamodel.html

答案 1 :(得分:18)

答案 2 :(得分:3)

虽然问题已经得到解答;如果有人对解决方法感兴趣,这是一个例子 -

mydate = datetime.date(2013, 3, 26)
mydate.special = 'Some special date annotation'  # doesn't work
...
class CustomDate(datetime.date):
    pass
mydate = datetime.date(2013, 3, 26)
mydate = CustomDate(mydate.year, mydate.month, mydate.day)
mydate.special = 'Some special date annotation'  # works