我有这段代码:

>>> 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 并不特别感兴趣。我一直在想对象。

有帮助吗?

解决方案

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

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

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

其他提示

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

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top