newb question about @property

Paul Moore p.f.moore at gmail.com
Wed Oct 4 12:52:29 EDT 2017


On 4 October 2017 at 17:02, Rhodri James <rhodri at kynesim.co.uk> wrote:
> Actually you can:
>
>>>> class Point:
> ...   __slots__ = ("x", "y")
> ...   def __init__(self, x, y):
> ...     self.x = x
> ...     self.y = y
> ...   def __str__(self):
> ...     return "({0},{1})".format(self.x, self.y)
> ...
>>>> p = Point(3,4)
>>>> print(p)
> (3,4)
>>>> print(p.x)
> 3
>>>> p.x = 7
>>>> print(p)
> (7,4)
>>>> p.z = 2
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'Point' object has no attribute 'z'
>
> I pretty much never bother to do this because (bart to the contrary) it
> isn't useful if you're thinking in Pythonic terms, but it can be done pretty
> easily.

Good point. I'd forgotten that - like you say, it's not common to want
to constrain things to this level in idiomatic Python code.
Paul



More information about the Python-list mailing list