【问题标题】:Is it possible to assign a setter function to an object attribute without the @x.setter decorator?是否可以在没有 @x.setter 装饰器的情况下将 setter 函数分配给对象属性?
【发布时间】:2017-04-12 12:09:24
【问题描述】:

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

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,则(当然)不会执行相应的格式化功能。我可以在不使用@property-decorator 和str_to_date() / str_to_price() 分别使用@date.setter- / @price.setter-decorator 明确编写dateprice 的情况下以某种方式做到这一点吗?

【问题讨论】:

  • This 可能与您有些相关。
  • 你为什么想要在没有property的情况下这样做?您根本不想使用描述符吗?
  • @jonrsharpe 我有类似的具有不同/更多格式化功能的类,这只是为了说明问题而进行的简化。我可以使用@property,但会产生大量冗余代码;我也想让它的类非常精简和灵活,这样就可以很容易地添加新的属性和格式化函数,而无需太多修改代码。
  • 你可以在__setattr__ 中执行此操作,我建议不要在每次创建实例时都更新字典。
  • @Kaleidophon 考虑到元编程方法,您可能希望使用descriptors

标签: python python-2.7 properties getter-setter


【解决方案1】:

感谢@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)

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2011-09-22
    • 2017-10-20
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多