Advanced Default Values
The Wikipedia page on Unicode input gives some help on how to enter Unicode characters. You can also enter the Unicode symbols for the suits using the
\u Unicode escapes or the
\n named characters escapes as seen onscreen. If you’re having problems entering these codes, they’re included in the course resource files to allow you to copy and paste the appropriate lines into your REPL.
As you can see, you shouldn’t do this. This would introduce one of the most common anti-patterns in Python: using mutable default arguments. The problem is that all instances of
Deck will use the same list object as the default value of the
This means that if, say, one card is removed from one
Deck, then it disappears from all other instances of
Deck as well. Data classes prevent you from doing this, as the code has raised a
ValueError. Instead, data classes use something called a
default_factory to handle mutable default values. To use
default_factory, and many other cool features of data classes, you need to use the
The argument to
default_factory can be any zero parameter callable. Now it’s easy to create a full deck of playing cards. The
field() specifier is used to customize each field of a data class individually.
You’ll see some other examples later. For reference, here are the parameters
default: the default value of the field.
default_factory: a function that returns the initial value of the field.
init: whether the field is used in the
.__init__() method. The default is
hash: include the field when calculating
hash(). The default is to use the same as for
metadata: a mapping with information about the field. In the
Position example, you saw how to add simple default values by writing
lat: float = 0.0. However, if you also want to customize the field, for instance to hide it in the
repr, you need to use the
default parameter as seen onscreen.
You may not specify both
metadata parameter is not used by the data classes themselves but is available for you or third party packages to attach information to fields. In the
Position example, you could, for instance, specify that latitude and longitude should be given in degrees.
Become a Member to join the conversation.