osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

newb question about @property


On 04/10/2017 17:02, Rhodri James wrote:
> On 04/10/17 16:33, Paul Moore wrote:

>> 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)

But it's something you'd have to explicitly do (unless perhaps you make 
use of those decorators, which AFAICS can do magic).

And when I tried, it didn't really work in Python 2 (extra attributes 
could still be created, and .__slots__ wasn't readonly); only Py3.

> it 
> isn't useful if you're thinking in Pythonic terms,

I clearly don't. When I do this in my non-Python language it would be just:

   record any = (var x,y)

   p := any(10,20)
   println p                  # (10,20)
   println p.y, p.x           # 20 10
   println p.len              # 2
   println p[2]               # 20
   println p = any(10,20)     # 1 (compares fields)

No __slots__, __init__ or __str__ need to be defined; it just works.

If I needed a version suitable for foreign function interfacing, a 
little different:

   type point = struct (real64 x,y)

   p := point(10,20)
   println p                  # (10.0000,20.0000)
   println p.bytes            # 16

It's not Pythonic, but it is pretty handy....

(I know Python can also do structs like this but it appeared to be quite 
a slog last time I looked.)

I guess my kind of coding is somewhat less esoteric than the kind of 
thing I typically see in Python here.

-- 
bartc