Where do classes get the default attributes of '__dict__'?

If we compare the lists generated by the built-in dir() for the superclass of the object and 'dummy', a bodyless class such as

 class A(): pass 

we find that class A has three attributes ('__dict__', '__module__' and '__weakref__') that are not in the object class.

Where does class A inherit these additional attributes from?

+7
source share
1 answer
  • The __dict__ attribute is generated by internal code in type.__new__ . A metaclass class can affect the final __dict__ content. If you use __slots__ , you will not have the __dict__ attribute.

  • __module__ set when the class compiles, so the instance inherits this attribute from the class. You can verify this by running the 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 different value from cls.__module__ . You don't know why this is not a readonly attribute.)

  • __weakref__ is created when an instance; AFAIK is fully controlled by CPython's internal object creation system. This attribute is present only in instances of object subclasses - for example, instances of int , list , set , tuple do not have the __weakref__ attribute.

    When interpreting this explanation, keep in mind that class C: equivalent to class C(object): for Python3. For Python2, a simple class C: will generate instances without __weakref__ (or several other attributes derived from the implementation of object ).

+8
source

All Articles