What causes user objects to not throw an AttributeError in Python?

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

The following code does not throw an AttributeError

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

This contrasts with

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

What is the difference? Is it that dict is an inline class while MyClass is user defined?

+5
source share
1 answer

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

class MyClass(object):
    __slots__ = []

, . , , .

+2

All Articles