diff options
author | Ethan Furman <ethan@stoneleaf.us> | 2020-09-22 07:05:27 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-22 07:05:27 (GMT) |
commit | 62e40d8450b9c78346ec3617de7fe3f0ad381510 (patch) | |
tree | 66a5a3479bd2e7a2198964be0f3fe9f7a617ef02 | |
parent | 40a0625792e795cd41c4ba20475e3b770b53817a (diff) | |
download | cpython-62e40d8450b9c78346ec3617de7fe3f0ad381510.zip cpython-62e40d8450b9c78346ec3617de7fe3f0ad381510.tar.gz cpython-62e40d8450b9c78346ec3617de7fe3f0ad381510.tar.bz2 |
Enum: add extended AutoNumber example (GH-22349)
-rw-r--r-- | Doc/library/enum.rst | 26 | ||||
-rw-r--r-- | Misc/ACKS | 1 |
2 files changed, 27 insertions, 0 deletions
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst index 843d961..3e9b1f9 100644 --- a/Doc/library/enum.rst +++ b/Doc/library/enum.rst @@ -925,6 +925,32 @@ Using an auto-numbering :meth:`__new__` would look like:: >>> Color.GREEN.value 2 +To make a more general purpose ``AutoNumber``, add ``*args`` to the signature:: + + >>> class AutoNumber(NoValue): + ... def __new__(cls, *args): # this is the only change from above + ... value = len(cls.__members__) + 1 + ... obj = object.__new__(cls) + ... obj._value_ = value + ... return obj + ... + +Then when you inherit from ``AutoNumber`` you can write your own ``__init__`` +to handle any extra arguments:: + + >>> class Swatch(AutoNumber): + ... def __init__(self, pantone='unknown'): + ... self.pantone = pantone + ... AUBURN = '3497' + ... SEA_GREEN = '1246' + ... BLEACHED_CORAL = () # New color, no Pantone code yet! + ... + >>> Swatch.SEA_GREEN + <Swatch.SEA_GREEN: 2> + >>> Swatch.SEA_GREEN.pantone + '1246' + >>> Swatch.BLEACHED_CORAL.pantone + 'unknown' .. note:: @@ -1723,6 +1723,7 @@ Févry Thibault Lowe Thiderman Nicolas M. Thiéry James Thomas +Reuben Thomas Robin Thomas Brian Thorne Christopher Thorne |