Limiting attribute names with __slots__

We can use __slots__ to create a class where we cannot add new attributes, but can modify an attribute's value. This example shows how to restrict the attribute names:

class BlackJackCard:
__slots__ = ("rank", "suit", "hard", "soft")

def __init__(self, rank: str, suit: "Suit", hard: int, soft: int) -> None:
self.rank = rank
self.suit = suit
self.hard = hard
self.soft = soft

We made one significant change to the previous definitions of this class: setting the __slots__ attribute to the names of the attributes allowed. This turns off the internal __dict__ feature of the object and limits us to these attribute names only. The defined attribute values are mutable even though new attributes cannot be added.

The primary use case for this feature is to limit the memory occupied by the internal __dict__ structure created by default. The __slots__ structure uses less memory, and is often used when a very large number of instances will be created.

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

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