简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM