Python Custom Classes¶
Decorators¶
@classmethod
¶
- the first param is the class
- instead of
self
(which is the instance)- which accesses the instance values
- or class values if it hasn't been overridden
Creating unique values¶
Unique sentinel values, identity checks, and when to use object() instead of None
[[spot-the-bug#The problem with None in Python]]
object()
¶
kinda Like JS Symbol
No two symbols are the same
Useful for creating unique values
Every class in Python has a base class of
object
When to use object
?¶
- Unique initial values: a starting value that should be distinguished from values seen later (
default
andinitial
in ourmin
function) - Unique stop values: a value whose presence tells us to stop looping/processing (a true sentinel value, as in
strict_zip
) - Unique skip values: a value whose presence should be treated as an empty value to be skipped over (we didn’t see this, but it comes up with utilities like
itertools.zip_longest
sometimes)
Enum¶
Regular enum¶
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
>>> Color.RED
<Color.RED: 1>
>>> Color.RED.name
'RED'
>>> Color.RED.value
1
string enum¶
same thing with IntEnum
(a built-in)
Last update:
2023-04-24