If we compare the lists generated by applying the dir()
built-in to the object superclass and to a 'dummy', bodyless class, such as
class A():
pass
we find that the A class has three attributes ('__dict__', '__module__' and '__weakref__')
that are not present in the object class.
Where does the A class inherit these additional attributes from?
The __dict__
attribute is created by the internal code in type.__new__
. The class's metaclass may influence the eventual content of __dict__
. If you are using __slots__
, you will have no __dict__
attribute.
__module__
is set when the class is compiled, so the instance inherits this attribute from the class. You can verify this by performing the test inst.__module__ is cls.__module__
(given that inst
is an instance of cls
), and also by modifying cls.__module__
and observing that inst.__module__
reflects this change.
(you can also do stupid things like setting inst.__module__
to a differing value from cls.__module__
. Not sure why this isn't a readonly attribute.)
__weakref__
is created when the instance is; AFAIK it's completely controlled by the internal CPython object-creation system. This attribute is only present on instances of object
subclasses -- for example instances of int
, list
, set
, tuple
have no __weakref__
attribute.
In interpreting this explanation, keep in mind that class C:
is equivalent to class C(object):
for Python3. For Python2, plain class C:
will generate instances without __weakref__
(or a number of other attributes acquired from the object
implementation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With