How is it possible that
class EmptyClass:
def __init__(self):
pass
e = EmptyClass()
e.a = 123
works and:
o = objec
You cannot add attributes to an instance of object
because object
does not have a __dict__ attribute (which would store the attributes). From the docs:
class object
Return a new featureless object.
object
is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.Note:
object
does not have a__dict__
, so you can’t assign arbitrary attributes to an instance of theobject
class.
And object
does have its uses:
As stated above, it serves as the base class for all objects in Python. Everything you see and use ultimately relies on object
.
You can use object
to create sentinel values which are perfectly unique. Testing them with is
and is not
will only return True
when an exact object
instance is given.
In Python 2.x, you can (should) inherit from object
to create a new-style class. New-style classes have enhanced functionality and better support. Note that all classes are automatically new-style in Python 3.x.