Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do classes get their default '__dict__' attributes from?

Tags:

python

class

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?

like image 457
Marcos Gonzalez Avatar asked May 12 '13 23:05

Marcos Gonzalez


1 Answers

  • 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).

like image 97
kampu Avatar answered Oct 06 '22 01:10

kampu