社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何根据某些条件自动设置python类属性值[重复]

Appyens • 6 年前 • 1682 次点击  

我有一个具有多个相关属性的类,例如:

class SomeClass:
    def __init__(self, n=0):
        self.list = range(n)
        self.listsquare = [ x**2 for x in self.list ]

如果我做一个正常的物体那没问题

a = SomeClass(10)

我要两张单子, a.list a.listsquare .

现在,如果我想先创建一个空对象,并为其分配一个属性,我希望其他属性自动更新,例如

b = SomeClass()
b.list = range(5,10)

我想要 b.listsquare 自动更新,也可以通过另一种方式(分配 B.列表框 和自动更新 b.list )。这可能吗?是 等级 这个选择对吗?


谢谢大家,但我完全被各种不同的答案所淹没。有谁能给我一个完整的解决方案,让我能学会自己写吗?

我想上一堂课 Foo 有三个属性 length , list listsquare 以便:

  1. 如果我做了 a = Foo(3) ,我明白了 a.length = 3 , a.list = [0, 1, 2] , a.listsquare = [0, 1, 4]
  2. 如果我做了 b = Foo().list = [5, 6] ,我明白了 b.length = 2 , b.listsquare = [25, 36]
  3. 如果我做了 c = Foo().listsquare = [4, 9] ,我明白了 c.length = 2 , c.list = [2, 3]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39928
文章 [ 4 ]  |  最新文章 6 年前