Creating immutable objects as a NamedTuple subclass

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.hard
1

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:

>>> c.not_allowed = 2
Traceback (most recent call last):
File "/Users/slott/miniconda3/envs/py37/lib/python3.7/doctest.py", line 1329, in __run
compileflags, 1), test.globs)
File "<doctest __main__.__test__.test_comparisons_2[3]>", line 1, in <module>
c.not_allowed = 2
AttributeError: 'AceCard2' object has no attribute 'not_allowed'
>>> c.rank = 3
Traceback (most recent call last):
File "/Users/slott/miniconda3/envs/py37/lib/python3.7/doctest.py", line 1329, in __run
compileflags, 1), test.globs)
File "<doctest __main__.__test__.test_comparisons_2[4]>", line 1, in <module>
c.rank = 3
AttributeError: can't set attribute
..................Content has been hidden....................

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