summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEthan Furman <ethan@stoneleaf.us>2018-09-12 17:00:30 (GMT)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2018-09-12 17:00:30 (GMT)
commitf52237400b9960d434c5d0676a3479b8c1e8c869 (patch)
tree3203eaba01ef1fdcd95a38d82f0a4b22627e8bd4
parent865c17fb28f8c3275fd94da6ee4ac51472ec874a (diff)
downloadcpython-f52237400b9960d434c5d0676a3479b8c1e8c869.zip
cpython-f52237400b9960d434c5d0676a3479b8c1e8c869.tar.gz
cpython-f52237400b9960d434c5d0676a3479b8c1e8c869.tar.bz2
bpo-33437: add __new__ vs __init__ example (GH-9145)
Improve Enum docs. https://bugs.python.org/issue33437
-rw-r--r--Doc/library/enum.rst31
-rw-r--r--Misc/ACKS1
2 files changed, 32 insertions, 0 deletions
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index 3f17f99..6408c01 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -736,6 +736,37 @@ Some rules:
type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
:func:`repr` is desired, use the `!s` or `!r` format codes.
+When to use :meth:`__new__` vs. :meth:`__init__`
+------------------------------------------------
+
+:meth:`__new__` must be used whenever you want to customize the actual value of
+the :class:`Enum` member. Any other modifications may go in either
+:meth:`__new__` or :meth:`__init__`, with :meth:`__init__` being preferred.
+
+For example, if you want to pass several items to the constructor, but only
+want one of them to be the value::
+
+ >>> class Coordinate(bytes, Enum):
+ ... """
+ ... Coordinate with binary codes that can be indexed by the int code.
+ ... """
+ ... def __new__(cls, value, label, unit):
+ ... obj = bytes.__new__(cls, [value])
+ ... obj._value_ = value
+ ... obj.label = label
+ ... obj.unit = unit
+ ... return obj
+ ... PX = (0, 'P.X', 'km')
+ ... PY = (1, 'P.Y', 'km')
+ ... VX = (2, 'V.X', 'km/s')
+ ... VY = (3, 'V.Y', 'km/s')
+ ...
+
+ >>> print(Coordinate['PY'])
+ Coordinate.PY
+
+ >>> print(Coordinate(3))
+ Coordinate.VY
Interesting examples
--------------------
diff --git a/Misc/ACKS b/Misc/ACKS
index 75047d8..0d9431d 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -68,6 +68,7 @@ Ammar Askar
Neil Aspinall
Chris AtLee
Aymeric Augustin
+Andres Ayala
Cathy Avery
John Aycock
Donovan Baarda