Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f522374

Browse files
ethanfurmanmiss-islington
authored andcommitted
bpo-33437: add __new__ vs __init__ example (GH-9145)
Improve Enum docs. https://bugs.python.org/issue33437
1 parent 865c17f commit f522374

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

Doc/library/enum.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,37 @@ Some rules:
736736
type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
737737
:func:`repr` is desired, use the `!s` or `!r` format codes.
738738

739+
When to use :meth:`__new__` vs. :meth:`__init__`
740+
------------------------------------------------
741+
742+
:meth:`__new__` must be used whenever you want to customize the actual value of
743+
the :class:`Enum` member. Any other modifications may go in either
744+
:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
745+
746+
For example, if you want to pass several items to the constructor, but only
747+
want one of them to be the value::
748+
749+
>>> class Coordinate(bytes, Enum):
750+
... """
751+
... Coordinate with binary codes that can be indexed by the int code.
752+
... """
753+
... def __new__(cls, value, label, unit):
754+
... obj = bytes.__new__(cls, [value])
755+
... obj._value_ = value
756+
... obj.label = label
757+
... obj.unit = unit
758+
... return obj
759+
... PX = (0, 'P.X', 'km')
760+
... PY = (1, 'P.Y', 'km')
761+
... VX = (2, 'V.X', 'km/s')
762+
... VY = (3, 'V.Y', 'km/s')
763+
...
764+
765+
>>> print(Coordinate['PY'])
766+
Coordinate.PY
767+
768+
>>> print(Coordinate(3))
769+
Coordinate.VY
739770

740771
Interesting examples
741772
--------------------

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Ammar Askar
6868
Neil Aspinall
6969
Chris AtLee
7070
Aymeric Augustin
71+
Andres Ayala
7172
Cathy Avery
7273
John Aycock
7374
Donovan Baarda

0 commit comments

Comments
 (0)