是否可以在没有 @x.setter 装饰器的情况下将 setter 函数分配给对象属性?
Is it possible to assign a setter function to an object attribute without the @x.setter decorator?
我有一个属性名称和函数的字典,用于在创建对象时格式化相应的值:
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])
但是如果我以后设置这些"special"属性如date
或price
,相应的格式化功能将(当然)不会被执行。我可以在不使用 @property
-装饰器明确编写 date
和 price
以及使用相应的 @date.setter
- / str_to_date()
/ str_to_price()
的情况下以某种方式执行此操作@price.setter
-装饰器?
感谢@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)
我有一个属性名称和函数的字典,用于在创建对象时格式化相应的值:
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])
但是如果我以后设置这些"special"属性如date
或price
,相应的格式化功能将(当然)不会被执行。我可以在不使用 @property
-装饰器明确编写 date
和 price
以及使用相应的 @date.setter
- / str_to_date()
/ str_to_price()
的情况下以某种方式执行此操作@price.setter
-装饰器?
感谢@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)