Skip to content

Commit 62e40d8

Browse files
authored
Enum: add extended AutoNumber example (GH-22349)
1 parent 40a0625 commit 62e40d8

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Doc/library/enum.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,32 @@ Using an auto-numbering :meth:`__new__` would look like::
925925
>>> Color.GREEN.value
926926
2
927927

928+
To make a more general purpose ``AutoNumber``, add ``*args`` to the signature::
929+
930+
>>> class AutoNumber(NoValue):
931+
... def __new__(cls, *args): # this is the only change from above
932+
... value = len(cls.__members__) + 1
933+
... obj = object.__new__(cls)
934+
... obj._value_ = value
935+
... return obj
936+
...
937+
938+
Then when you inherit from ``AutoNumber`` you can write your own ``__init__``
939+
to handle any extra arguments::
940+
941+
>>> class Swatch(AutoNumber):
942+
... def __init__(self, pantone='unknown'):
943+
... self.pantone = pantone
944+
... AUBURN = '3497'
945+
... SEA_GREEN = '1246'
946+
... BLEACHED_CORAL = () # New color, no Pantone code yet!
947+
...
948+
>>> Swatch.SEA_GREEN
949+
<Swatch.SEA_GREEN: 2>
950+
>>> Swatch.SEA_GREEN.pantone
951+
'1246'
952+
>>> Swatch.BLEACHED_CORAL.pantone
953+
'unknown'
928954

929955
.. note::
930956

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,6 +1723,7 @@ Févry Thibault
17231723
Lowe Thiderman
17241724
Nicolas M. Thiéry
17251725
James Thomas
1726+
Reuben Thomas
17261727
Robin Thomas
17271728
Brian Thorne
17281729
Christopher Thorne

0 commit comments

Comments
 (0)