Consider two versions of a simple weather model which stores the location of clouds:
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)
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()
This has basically been punished here Is it bad to store all instances of a class in a class field? but there is an emphasis here on class methods which act on all instances. Is there nothing to be said for the simplicity of the last three lines that the second approach affords?
I am aware that another approach would be creating a list-like class called, for example, collection and giving that class methods like update_all() but to me it doesn't seem much better.
Cloud.addObject(cloudObj)
, but here the objects are added automatically. – Tenrec