Slots

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}, {self.long})"

While this is an interesting feature, it has to be used with caution because it is taking away the dynamic nature of Python. In general, this ought to be reserved only for objects that we know are static, and if we are absolutely sure we are not adding any attributes to them dynamically in other parts of the code.

As an upside of this, objects defined with slots use less memory, since they only need a fixed set of fields to hold values and not an entire dictionary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.198.132