Search code examples
pythonpython-2.7propertiesgetter-setter

Is it possible to assign a setter function to an object attribute without the @x.setter decorator?


I have a dictionary of attribute names and functions used to format the corresponding values when the object is created:

class CoolClass(object):

    def __init__(self, **given):
        self.formatting_functions.update({
            "date": self.str_to_date,
            "price": self.str_to_price
        })

        for attribute_name in given:
            if attribute_name in self.formatting_functions:
                formatting_function = self.formatting_functions[attribute_name]
                setattr(
                    self, attribute_name,
                    formatting_function(given[attribute_name])
                )
            else:
                setattr(self, attribute_name, given[attribute_name])

But if I will set these "special" attributes like date or price later, the corresponding formatting function will (of course) not be executed. Can I do this somehow without explicitly writing date and price with the @property-decorator and str_to_date() / str_to_price() with the respective @date.setter- / @price.setter-decorator?


Solution

  • Thanks to @EliSadoff and @Jonrsharpe! I just implemented a solution overwriting setattr:

    def __setattr__(self, name, value):
        if hasattr(self, "formatting_functions"):
            if name in self.formatting_functions:
                formatting_function = self.formatting_functions[name]
                value = formatting_function(value)
        super(CoolClass, self).__setattr__(name, value)