diff options
| author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2020-09-23 03:58:32 (GMT) |
|---|---|---|
| committer | Łukasz Langa <lukasz@langa.pl> | 2020-10-04 17:19:18 (GMT) |
| commit | e8165e79f57cb3ca60bf031c417f8fd20c99eaa2 (patch) | |
| tree | ce4401b2073e1c7686d5081dac321dc3fab7c4ed | |
| parent | c549527ae2cc4b5934dbe80fea127fb04ff65af5 (diff) | |
| download | cpython-e8165e79f57cb3ca60bf031c417f8fd20c99eaa2.zip cpython-e8165e79f57cb3ca60bf031c417f8fd20c99eaa2.tar.gz cpython-e8165e79f57cb3ca60bf031c417f8fd20c99eaa2.tar.bz2 | |
bpo-37062: Enum: add extended AutoNumber example (GH-22349) (GH-22370)
(cherry picked from commit 62e40d8450b9c78346ec3617de7fe3f0ad381510)
Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
| -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 5f0762e..a3c5165 100644 --- a/Doc/library/enum.rst +++ b/Doc/library/enum.rst @@ -887,6 +887,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:: @@ -1713,6 +1713,7 @@ Févry Thibault Lowe Thiderman Nicolas M. Thiéry James Thomas +Reuben Thomas Robin Thomas Brian Thorne Christopher Thorne |
