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.
How is it possible? The explanation you are getting this error is that you are naming the setter method mistakenly. You have named the setter method as set_x which is off base, this is the reason you are getting the Attribute Error.
Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.
Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With