社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Benjamin Ibhar

Benjamin Ibhar 最近创建的主题
Benjamin Ibhar 最近回复了
11 年前
回复了 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]