我有一个属性名称和函数的字典,用于在创建对象时格式化相应的值:
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])
但是如果我稍后会设置这些“特殊”属性,例如date
或price
,则相应的格式化功能(当然)不会被执行。如果没有明确地将date
和price
与@property
- 装饰者和str_to_date()
/ str_to_price()
分别写为@date.setter
- /我可以这样做吗? @price.setter
- ?装饰
答案 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)