Content deleted Content added
m →Python: Update Python example code from deprecated Python 2 to Python 3 |
m →Python: Python has new options for building immutable objects, including typing.NamedTuple and dataclasses. Add new code examples with references, and refactor old code examples. |
||
Line 305:
__delattr__ = __setattr__
def __init__(self, x, y)
# We can no longer use self.value = value to store the instance data
# so we must explicitly call the superclass
Line 312:
</syntaxhighlight>
The standard library
<syntaxhighlight lang="python">
from typing import NamedTuple
import collections
Point = collections.namedtuple('Point', ['x', 'y'])
# the following creates a similar namedtuple to the above
class Point(NamedTuple):
x: int
y: int
</syntaxhighlight>
Introduced in Python 3.7, [https://docs.python.org/3/library/dataclasses.html dataclasses] allow developers to emulate immutability with [https://docs.python.org/3/library/dataclasses.html#frozen-instances frozen instances]. If a frozen dataclass is built, dataclasses will override __setattr__() and __delattr__() to raise FrozenInstanceError if invoked.
<syntaxhighlight lang="python">
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
</syntaxhighlight>
=== JavaScript ===
|