5

Possible Duplicate:
Why can't I directly add attributes to any python object?
Why can't you add attributes to object in python?

The following code does not throw AttributeError

class MyClass():
    def __init__(self):
        self.a = 'A'
        self.b = 'B'
my_obj = MyClass()
my_obj.c = 'C'

That contrasts with

>>> {}.a = 'A'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'a'

What makes such difference? Is it about dict being a built-in class while MyClass being user defined?

Community
  • 1
  • 1
Le Curious
  • 1,331
  • 1
  • 12
  • 13
  • 1
    The real question is more *what makes some objects throw AttributeErrors when setting* - Python is dynamic, so it's natural you should be able to do this, not the other way around. – Gareth Latty Jun 06 '12 at 11:43
  • possible duplicate: http://stackoverflow.com/questions/1285269/why-cant-you-add-attributes-to-object-in-python http://stackoverflow.com/questions/1072649/python-language-question-attributes-of-object-vs-function – mgilson Jun 06 '12 at 11:44
  • The first link given by mgilson above has a good answer. – Sven Marnach Jun 06 '12 at 12:05

1 Answers1

2

The difference is that instances of user-defined classes have a dictionary of attributes associated with them by default. You can access this dictionary using vars(my_obj) or my_obj.__dict__. You can prevent the creation of an attribute dictionary by defining __slots__:

class MyClass(object):
    __slots__ = []

Built-in types could also provide an attribute dictionary, but usually they don't. An example of a built-in type that does support attributes is the type of a function.

Sven Marnach
  • 483,142
  • 107
  • 864
  • 776