mardi 16 mars 2021

Python dynamically add property always returns same result

I'm relatively new to python. I created this minimal sample to demonstrate my problem. Within a loop I add some properties to my class during runtime. If I query the properties later I always get the same result. I printed and checked the function instance variables of the function and the property and they all differ as expected. When I invoke the properties I always end up in the result of the last property.

class T:
    def __init__(self):
        specialList = ['MIN', 'DEF', 'MAX']
        for special in specialList:  
            def get_property_special(self):
                print('return get_current('+special+')') #call getter with special parameter
                return special # just fake here. Should return value of getter
            
            print("Dyn function", get_property_special)
            specialProp = property()
            print("Property "+ str(specialProp))
            specialProp = specialProp.getter(get_property_special)
            setattr(T, "current_" + special.lower(), specialProp)
            print ("define property: current_" + special.lower())
               
b = T()
print(b.current_max)
print(b.current_min)
print(b.current_def)

Results in:

Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8805E0>
Property <property object at 0x0000026D6D8929A0>
define property: current_min
Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8A9790>
Property <property object at 0x0000026D6D892AE0>
define property: current_def
Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8A94C0>
Property <property object at 0x0000026D6D892B30>
define property: current_max
get_current(MAX) #ok
MAX
get_current(MAX) #Error: why MAX called min
MAX
get_current(MAX) #Error: why MAX called def
MAX

Edit: I want the property to call the getter with the parameter MIN, MAX, DEF





Aucun commentaire:

Enregistrer un commentaire