python引用类似函数的属性

2024-03-28 13:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何pythonical设置多个属性而不单独引用它们?下面是我的解决方案。在

class Some_Class(object):

    def __init__(self):
        def init_property1(value): self.prop1 = value
        def init_property2(value): self.prop2 = value

        self.func_list = [init_property1, init_property2]

    @property
    def prop1(self):
        return 'hey im the first property'

    @prop1.setter
    def prop1(self, value):
        print value

    @property
    def prop2(self):
        return 'hey im the second property'

    @prop2.setter
    def prop2(self, value):
        print value


class Some_Other_Class(object):

    def __init__(self):

        myvalues = ['1 was set by a nested func','2 was set by a nested func']
        some_class= Some_Class()

        # now I simply set the properties without dealing with them individually
        # this assumes I know how they are ordered (in the list)
        # if necessary, I could use a map

        for idx, func in enumerate(some_class.func_list):
            func(myvalues[idx])

        some_class.prop1 = 'actually i want to change the first property later on'

if __name__ == '__main__':
    test = Some_Other_Class()

当我有许多属性要用用户定义的值初始化时,这就变得很有必要了。否则,我的代码看起来就像是一个单独设置每个属性的巨大列表(非常混乱)。在

请注意,下面很多人都有很好的答案,我想我已经找到了一个好的解决方案。这是一个重新编辑主要是为了清楚地说明问题。但是,如果有人有更好的方法请分享!在


Tags: theself属性initvaluedefpropertysome
3条回答

我。。。最后我想我知道你想做什么,你不需要用你接近它的方式去做。让我试试这个。在

class someclass(object):

    def __init__(self):
        func_list = [self.setter1, self.setter2]
        value_list = [1, 2]
        #    These lines don't need to be this complicated.
        #    for ind in range(len(func_list)): 
        #        func_list[ind](value_list[ind])

        for idx, func in enumerate(func_list):
            func(value_list[idx])

        #  Or even better
        for idx, (func, val) in enumerate(zip(func_list, value_list)):
            func(val)

    def setter1(self, value): 
        self.a = value

    def setter2(self, value): 
        self.b = value

值得指出的是,idx变量和enumerate调用在第二种形式中是多余的,但我不确定您是否需要在其他地方使用它。在

只需使用@property decorator

>>> class A:
...    a=2
...    @property
...    def my_val(self,val=None):
...        if val == None:return self.a
...        self.a = val
...
>>> a=A()
>>> a.my_val
2
>>> a.my_val=7
>>> a.my_val
7

像这样?在

如果你只想允许设置,那么不要给它一个默认值

^{pr2}$

或者如果您只想允许检索,只需命令第二个参数

>>> class A:
...    a=2
...    @property
...    def my_val(self):
...        return self.a
...      
...
>>> a=A()
>>> a.my_val
2
>>> a.my_val=7
<Exception>

如果您在对象dict中查找属性,您将得到属性描述符(如果有的话),类也是如此;例如

a = SomeClass()
descriptor = a.__dict__.get('descriptor', type(a).__dict__.get('descriptor'))

假设descriptor是一个描述符,它将具有以下方法:

^{pr2}$

注意fget和{}。在

相关问题 更多 >