[Python] Dynamically Added Class Attributes with Getter/Setter Methods in a Loop in Python

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to dynamically assign class attributes to an existing custom class. These attributes have individual getter and setter methods defined in a loop across all attributes to be created and are assigned with setattr() within the loop. Please see code below.

    If I use setattr(), the newly created attributes point towards the last attribute that was created in the list. Whereas if I use setattr() within an eval() statement, it works correctly, i.e. each attribute pointing towards its own value.

    I think I kinda understand why - something about the scope of the functions and setattr() in the loop - but I can't really formulate it into words. Can someone smarter than me please give a formal explanation about what is going on and if there is a cleaner solution than using eval()?

    for attr in attr_list:
    def getter(self):
    return getattr(self, attr)

    def setter(self, value):
    setattr(self, attr, value)

    # DOES NOT WORK
    setattr(self.__class__, attr, property(getter, setter))

    # WORKS
    eval(f'setattr(self.__class__, \'{attr}\', property(lambda self: getattr(self, \'{attr}\'), lambda self, value: setattr(self, {attr}, value)))')

    Continue reading...

Compartilhe esta Página