June 2019
Beginner to intermediate
770 pages
19h 24m
English
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. ...
Read now
Unlock full access