是否可以在没有@ x.setter装饰器的情况下为一个对象属性分配一个setter函数?

时间:2016-11-28 17:14:50

标签: python python-2.7 properties getter-setter

我有一个属性名称和函数的字典,用于在创建对象时格式化相应的值:

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])

但是如果我稍后会设置这些“特殊”属性,例如dateprice,则相应的格式化功能(当然)不会被执行。如果没有明确地将dateprice@property - 装饰者和str_to_date() / str_to_price()分别写为@date.setter - /我可以这样做吗? @price.setter - ?装饰

1 个答案:

答案 0 :(得分:0)

感谢@EliSadoff和@Jonrsharpe!我刚刚实施了覆盖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)