finefoot
finefoot

Reputation: 11282

Difference between an instance of an empty class and an instance of object?

I created the following empty class A and an instance a of that class:

>>> class A:
...     pass
... 
>>> a = A()

As far as I understand, omitting base classes results in the class inheriting from object. I tried to verify this with:

>>> a.__class__.__bases__
(<class 'object'>,)

So I also created an instance of object:

>>> b = object()

However, comparing a and b, I noticed that using dir to get each objects attributes results in different lists for a and b:

>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> dir(b)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

a contains every attribute from b and an additional three more. The additional attributes only found in a are:

>>> set(dir(a)).difference(set(dir(b)))
{'__module__', '__dict__', '__weakref__'}

Where do they come from if class A is empty and inherits from object?

Upvotes: 1

Views: 210

Answers (1)

chepner
chepner

Reputation: 532208

Even if A is empty, it is still a user-defined class, which has some distinct differences from object (a necessarily implementation-defined class).

Upvotes: 2

Related Questions