Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attributes to python objects

It's a thing that bugged me for a while. Why can't I do:

>>> a = "" >>> a.foo = 2 Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'foo' 

...while I can do the following?

>>> class Bar(): ...     pass ...  >>> a = Bar() >>> a.foo = 10 #ok! 

What's the rule here? Could you please point me to some description?

like image 335
mik01aj Avatar asked May 06 '11 07:05

mik01aj


People also ask

Can you add an attribute to an object in Python?

While working with objects, there may be many situations where we need to add a new attribute to an object in the middle of the program. Python provides a function setattr() that can easily set the new attribute of an object. This function can even replace the value of the attribute.

Does Python object have attributes?

Since everything in Python is an object and objects have attributes (fields and methods), it's natural to write programs that can inspect what kind of attributes an object has. For example, a Python program could open a socket on the server and it accepts Python scripts sent over the network from a client machine.

How do you add elements to an object in Python?

To add a single element to a list in Python at the end, you can simply use the append() method. It accepts one object and adds that object to the end of the list on which it is called.


1 Answers

You can add attributes to any object that has a __dict__.

  • x = object() doesn't have it, for example.
  • Strings and other simple builtin objects also don't have it.
  • Classes using __slots__ also do not have it.
  • Classes defined with class have it unless the previous statement applies.

If an object is using __slots__ / doesn't have a __dict__, it's usually to save space. For example, in a str it would be overkill to have a dict - imagine the amount of bloat for a very short string.

If you want to test if a given object has a __dict__, you can use hasattr(obj, '__dict__').

This might also be interesting to read:

Some objects, such as built-in types and their instances (lists, tuples, etc.) do not have a __dict__. Consequently user-defined attributes cannot be set on them.

Another interesting article about Python's data model including __dict__, __slots__, etc. is this from the python reference.

like image 163
ThiefMaster Avatar answered Oct 01 '22 21:10

ThiefMaster