Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 478
Geo Avatar asked Mar 08 '09 12:03

Geo


People also ask

Can not set attribute Python?

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.

How do you add attributes in Python?

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.

Are attributes directly available in Python?

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.


1 Answers

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

like image 188
Epcylon Avatar answered Nov 11 '22 19:11

Epcylon