Search code examples
pythonclass-structure

Why can't I assign to undeclared attributes of an object() instance but I can with custom classes?


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.


Solution

  • 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'
    >>>