August 2018
Intermediate to advanced
332 pages
9h 12m
English
When a class defines the __slots__ attribute, it can contain all the attributes that the class expects and no more.
Trying to add extra attributes dynamically to a class that defines __slots __ will result in an AttributeError. By defining this attribute, the class becomes static, so it will not have a __dict__ attribute where you can add more objects dynamically.
How, then, are its attributes retrieved if not from the dictionary of the object? By using descriptors. Each name defined in a slot will have its own descriptor that will store the value for retrieval later:
class Coordinate2D: __slots__ = ("lat", "long") def __init__(self, lat, long): self.lat = lat self.long = long def __repr__(self): return f"{self.__class__.__name__}({self.lat}, ...