收集类变量中的所有实例总是不好的吗?

Sve*_*ugh 6 python class global-variables class-method class-members

考虑两个版本的简单天气模型,它存储云的位置:

class cloud:
    def __init__(self, x, y):
        self.x = x
        self.y = y

collection = []
collection.append(cloud(1,2))
collection.append(cloud(4,6))

def update_all_clouds(collection):
    for c in collection:
        cloud.x += 1
        cloud.y += 1

update_all_clouds(collection)
Run Code Online (Sandbox Code Playgroud)

VS

class cloud:
    collection = []
    def __init__(self, x, y)
        self.x = x
        self.y = y
        cloud.collection.append(self)
    @classmethod
    def update_all(cls):
        for c in cloud.collection:
            c.x += 1
            c.y += 1
cloud(1,2)
cloud(4,6)
cloud.update_all()
Run Code Online (Sandbox Code Playgroud)

这基本上受到了惩罚在 类字段中存储类的所有实例是不是很糟糕? 但是这里强调的是对所有实例起作用的类方法.对于第二种方法提供的最后三行的简单性,没有什么可说的吗?

我知道另一种方法是创建一个类似于列表的类,例如,集合并给出类似update_all()的类方法,但对我而言似乎并没有好多了.

shx*_*hx2 3

这个问题可以简单地简化为有关使用全局变量的问题,因为可变的类级成员只是不同名称空间中的全局变量。

所有反对使用全局变量的论点也适用于此。