mirror of
https://github.com/python/cpython.git
synced 2025-11-12 23:16:47 +00:00
Enum: add extended AutoNumber example (GH-22349)
This commit is contained in:
parent
40a0625792
commit
62e40d8450
2 changed files with 27 additions and 0 deletions
|
|
@ -925,6 +925,32 @@ Using an auto-numbering :meth:`__new__` would look like::
|
||||||
>>> Color.GREEN.value
|
>>> Color.GREEN.value
|
||||||
2
|
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::
|
.. note::
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1723,6 +1723,7 @@ Févry Thibault
|
||||||
Lowe Thiderman
|
Lowe Thiderman
|
||||||
Nicolas M. Thiéry
|
Nicolas M. Thiéry
|
||||||
James Thomas
|
James Thomas
|
||||||
|
Reuben Thomas
|
||||||
Robin Thomas
|
Robin Thomas
|
||||||
Brian Thorne
|
Brian Thorne
|
||||||
Christopher Thorne
|
Christopher Thorne
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue