property

Barry Scott barry at barrys-emacs.org
Fri Jun 26 08:56:25 EDT 2020



> On 26 Jun 2020, at 08:02, ast <ast at invalid> wrote:
> 
> 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
> 
> In the second code, I just changed the names of the
> decorated functions

It seems you have to change all the fahenheit to f for this to work.
You left 3.

> 
> Unforunately I was not able to find "property" source
> code to understand how it works exactly

I see these docs:

https://docs.python.org/3/library/functions.html?highlight=property#property <https://docs.python.org/3/library/functions.html?highlight=property#property>

which do not show your usage.

The code is here:

https://github.com/python/cpython/blob/master/Objects/descrobject.c <https://github.com/python/cpython/blob/master/Objects/descrobject.c>

It defines the PyProperty_Type that is the builtin property class.

Barry

> 
> I wrote a my_property which makes the two previous codes
> to work fine. This is why I don't understand why the
> genuine property does't work when decorated functions
> are named f rather than fahrenheit
> 
> Here it is:
> 
> class my_property:
> 
>    def __init__(self, fget=None, fset=None, fdel=None):
>        self.fget = fget
>        self.fset = fset
>        self.fdel = fdel
> 
>    def __get__(self, instance, owner):
>        if instance is None:
>            return self
>        return self.fget(instance)
> 
>    def __set__(self, instance, value):
>        self.fset(instance, value)
> 
>    def __delete__(self, instance):
>        self.fdel(instance)
> 
>    def getter(self, fget):
>        self.fget = fget
>        return self
> 
>    def setter(self, fset):
>        self.fset = fset
>        return self
> 
>    def deleter(self, fdel):
>        self.fdel = fdel
>        return self
> -- 
> https://mail.python.org/mailman/listinfo/python-list <https://mail.python.org/mailman/listinfo/python-list>



More information about the Python-list mailing list