简体   繁体   中英

Why can't I directly add attributes to any python object?

I have this code:

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

And this code:

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

From my Python knowledge, I would say that datetime overrides setattr / getattr , but I am not sure. Could you shed some light here?

EDIT: I'm not specifically interested in datetime . I was wondering about objects in general.

My guess, is that the implementation of datetime uses __slots__ for better performance.

When using __slots__ , the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.

Read more here: http://docs.python.org/reference/datamodel.html

It's written in C

http://svn.python.org/view/python/trunk/Modules/datetimemodule.c?view=markup

It doesn't seem to implement setattr.

While the question has already been answered; if anyone is interested in a workaround, here's an example --

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM