Something annoying about method __set_name__ in descriptors
ast
ast at invalid
Tue Apr 21 08:27:29 EDT 2020
Hello
From python version 3.6, there is a useful new method
__set_name__ which could be implemented in descriptors.
This method is called after a descriptor is instantiated
in a class. Parameter "name" is filled with the name
of the attribute refering to the descriptor in the class
Here is an example:
class Descriptor:
def __set_name__(self, owner, name):
print(name)
class A:
value = Descriptor()
value ## produced by print in Descriptor
-----------------
But I discovered that __set_name__ is not called immediately
after the execution of line "value = Descriptor()" but after
all class code execution ...
Here is an other example:
class Descriptor:
def __set_name__(self, owner, name):
print("From Descriptor's method __set_name__: ", name)
class Test:
aaa = Descriptor()
print("From class Test")
From class Test
From Descriptor's method __set_name__: aaa
>>>
As you see, the print from __set_name__ occurs AFTER the print
from the class, I think every body was expecting the print
from __set_name__ before.
It is annoying in some real life, when one descriptor's method
is a decorator and you write things like:
class Temperature:
def __init__(self):
self.celsius= 0
fahrenheit = my_property()
@fahrenheit.getter
def fahrenheit(self):
return 1.8*self.celsius+ 32
@fahrenheit.setter
def fahrenheit(self, value):
self.celsius= (value -32)/1.8
and fahrenheit.getter is expecting an attribute in fahrenheit which
has not been set yet, it will be after all Temperature class code
execution ...
More information about the Python-list
mailing list