多个属性具有相同的GET属性

时间:2018-11-16 11:49:09

标签: python dynamic properties attributes

我最近听说过属性,可以在类中为属性的getter或setter分配函数。因此,您可以评估支票或其他内容的价值。

我想问一下是否可以为多个属性的getter分配相同的功能。为此,该函数需要动态返回,以便在调用X时返回值X,在调用Y时返回值Y。

我可以为每个属性做一个自己的吸气剂,但对于我来说,有20多个需要调用该函数的属性,因此进行动态调用会更好。

使用__getattributes__进行测试是一场彻底的灾难,因为我总是无休止地循环进行测试,所以这是不可能的,或者我只是犯了错误。

有可能吗?像这样:

class example():
    def __init__(self):
        self.__x = 1
        self.__y = 2

    def do_something(self):
        #Do something which is needed by multiple attributes
        #without changes
        attribute_name = '__' + attribute_name
        return self.__dict__[attribute_name]

    x = property(fget=do_something)
    y = property(fget=do_something)
    ...

编辑1:

我可能需要动态属性Getter的完整代码。 https://repl.it/@TobiasWagner/TV-DB-Django

0 个答案:

没有答案
相关问题