For custom classes (defined using the class keyword in regular Python code), the class will always have __slots__ in the class, __dict__ in the instance, or both (if one of the specified slots is '__dict__' , or one of the user-defined classes in the inheritance chain defines __slots__ , and the other is not, creating __dict__ implicitly). So three of the four possibilities cover user-defined classes.
Edit: Correction: technically a custom class cannot have either ; the class will be defined using __slots__ , but delete it after the definition time (the mechanism that sets the type does not require __slots__ to __slots__ saved after the class definition is complete). No sane person should do this, and he may have unwanted side effects (complete behavior unverified), but it is possible.
For built-in types, at least in the CPython reference interpreter, they hardly have __slots__ (if that were the case, then it would be to simulate a custom class that defines it is really nothing useful). The built-in type typically saves its attributes as C-level source values ββand pointers to a C-level structure, optionally with explicitly created descriptors or access methods, which excludes the purpose of __slots__ , which are just a convenient equivalent equivalent to struct games for custom classes. __dict__ is an option for built-in types, not the default (although the commissioning process is quite simple, you need to put the PyObject* entry somewhere in the structure and provide it with an offset in the type definition).
To be clear, __dict__ must not appear in a class so that it appears in its instances; __slots__ is a class level and can suppress __dict__ in an instance, but does not affect whether the class itself has __dict__ ; custom classes always have __dict__ , but their instances will not be if you use __slots__ .
In short:
(Sane) User-defined classes have at least one of __dict__ (in instances) or __slots__ (in the class) and can have both. Crazy custom classes did not have a single one, but only an abnormal developer could do this.
Built-in classes often do not, can provide __dict__ and almost never provide __slots__ , since it makes no sense to them.
Examples:
ShadowRanger Oct 04 '17 at 10:49 on 2017-10-04 22:49
source share