Py学习  »  Benjamin Ibhar  »  全部回复
回复总数  1
12 年前
回复了 Benjamin Ibhar 创建的主题 » 如何根据某些条件自动设置python类属性值[重复]

ignacio的@property解决方案很好,但它会在每次引用listsquare时重新计算列表-这可能会变得很昂贵。Mathew的解决方案很好,但是现在有了函数调用。您可以将这些与“property”函数结合起来。在这里,我为我的清单定义了一个getter和一个setter(我只是不能称之为'list'!)生成listsquare:

class SomeClass(object):

    def __init__(self, n=5):
        self.my_list = range(n)

    def get_my_list(self):
        return self._my_list

    def set_my_list(self, val):
        self._my_list = val
        # generate listsquare when my_list is updated
        self.my_listsquare = [x**2 for x in self._my_list]

    # now my_list can be used as a variable
    my_list = property(get_my_list, set_my_list, None, 'this list is squared')

x = SomeClass(3)
print x.my_list, x.my_listsquare
x.my_list = range(10)
print x.my_list, x.my_listsquare

这将输出:

[0, 1, 2] [0, 1, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]