views:

21

answers:

1

Basically I want to know why this works:

class MyClass:
  pass

myObj = MyClass()
myObj.foo = 'a'

But this returns an AttributeError:

myObj = object()
myObj.foo = 'a'

How can I tell which classes I can use undefined attributes with and which I can't?

Thanks.

+2  A: 

You can set attributes on any class with a __dict__, because that is where they are stored. object instances (which are weird) and any class that defines __slots__ do not have one:

>>> class Foo(object): pass
...
>>> foo = Foo()
>>> hasattr(foo, "__dict__")
True
>>> foo.bar = "baz"
>>>
>>> class Spam(object):
...     __slots__ = tuple()
...
>>> spam = Spam()
>>> hasattr(spam, "__dict__")
False
>>> spam.ham = "eggs"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Spam' object has no attribute 'ham'
>>>
katrielalex
i.e., any user-defined class will do
pberkes
@pberkes: nope, you can make classes without a `__dict__` (usually used for memory efficiency if you're expecting _lots_ of instances.
katrielalex
@katrielatex: I see... good to know!
pberkes