June 2019
Beginner to intermediate
770 pages
19h 24m
English
The best approach in terms of creating immutable objects is to make our Card property a subclass of typing.NamedTuple.
The following is an extension to the built-in typing.NamedTuple class:
class AceCard2(NamedTuple): rank: str suit: Suit hard: int = 1 soft: int = 11 def __str__(self) -> str: return f"{self.rank}{self.suit}"
When we use the preceding code, we see the following kinds of interaction:
>>> c = AceCard2("A", Suit.Spade)>>> c.rank'A'>>> c.suit<Suit.Spade: '♠'>>>> c.hard1
We can create an instance, and it has the desired attribute values. We cannot, however, add or change any attributes. All of the processing of attribute names is handled by the NamedTuple class definition:
>>> ...Read now
Unlock full access