On 04/10/17 16:33, Paul Moore wrote:
On 4 October 2017 at 16:03, bartc<b...@freeuk.com> wrote:
No error. Some would perceive all this as an advantage, but it means you
can't just declare a lightweight struct or record 'Point' with exactly two
fields x and y. You have to use other solutions ('namedtuples' or whatever,
which probably are immutable so that don't work the same way).
This is another example of neglecting the basics, but going for more
advanced, perhaps more sexy features instead.
It's another example of a consistent design philosophy (highly dynamic
classes) that you might not like - possibly even enough that Python
isn't the best language for you.
It's not an advantage or a disadvantage, just an approach. Many people
like it, you may not. Specifically, yes you can't "just declare a
lightweight struct or record with exactly two fields".
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.
--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list