property
Dieter Maurer
dieter at handshake.de
Fri Jun 26 13:57:58 EDT 2020
ast wrote at 2020-6-26 09:02 +0200:
>Hello,
>
>I am wondering why this code is OK:
>
>class Temperature:
> def __init__(self):
> self.celsius = 0
>
> fahrenheit = property()
>
> @fahrenheit.getter
> def fahrenheit(self):
> return 9/5*self.celsius +32
>
> @fahrenheit.setter
> def fahrenheit(self, value):
> self.celsius = (value-32)*5/9
>
>
>and this one is not:
>
>
>class Temperature:
> def __init__(self):
> self.celsius = 0
>
> fahrenheit = property()
>
> @fahrenheit.getter
> def f(self):
> return 9/5*self.celsius +32
>
> @fahrenheit.setter
> def f(self, value):
> self.celsius = (value-32)*5/9
A decoration
@dec...
def f(...): ...
is a shorthand notation for
def f(...): ...
f = dec...(f)
In your first example, "fahrenheit" is defined as you expect.
In the second example, some property functions are bound to `f`.
It depends on implementation details, whether the final
`f` and/or `fahrenheit` has both getter/setter definitions.
Always use the same name for function and property (as you do in
your first class).
More information about the Python-list
mailing list