newb question about @property

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Wed Oct 4 16:06:52 EDT 2017


On Wed, Oct  4, 2017 14:03 PM, bartc <bc at freeuk.com> wrote >
"A property, in some object-oriented programming languages, is a special 
>sort of class member, intermediate in functionality between a field (or 
>data member) and a method."
>
>But Python has some problems just in using fields. If you wanted say a 
>data type with two fields called x and y, then AFAIK you just create any 
>suitable class, but you don't need to specifically declare those two fields:
>
>  class any():
>      pass
>
>  p=any()
>  p.x=10
>  p.y=20
>
>But you also do this:
>
>  p.z=30
>
>and it magically acquires a third field! Or you want to modify p.x, but 
>accidentally type:
>
>  p.c=40
>
>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.
>
>Result? You can't just look at my 'any' class and see what fields it 
>uses. You can't even just look at the static source code. You have to 
>run the program to find out. And it might be different each time.
>
>



I think you might be missing a small feature buried in the language:

class any():..  __slots__ = ["x","y"]

>>> p = any()
>>> p.x = 10
>>> p.y = 20
>>> p.z = 30
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    p.z = 30
AttributeError: 'any' object has no attribute 'z'
>>> p.c = 40
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    p.c = 40
AttributeError: 'any' object has no attribute 'c'

 >>> p.__slots__
['x', 'y']   

So, you can prevent new fields from being added
without forcing yourself into an immutable named tuple.

And if you really need to know what is in there, it tells you!

Oh, and as regards to it being different each time:
>>> p.__slots__ = ['x','y','z']

Traceback (most recent call last):
 File "<pyshell#30>", line 1, in <module>

    p.__slots__ = ['x','y','z']

AttributeError: 'any' object attribute '__slots__' is read-only

Oh, and here's a little thing from the Python 3.6.2 Glossary:

__slots__ 

A declaration inside a class that saves memory by pre-declaring space for 
instance attributes and 
eliminating instance dictionaries. Though popular, the 
technique is somewhat tricky to get right and 
is best reserved for rare cases 
where there are large numbers of instances in a memory-critical application. 


Roger Christman
Pennsylvania State University




More information about the Python-list mailing list