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()的类方法,但对我而言似乎并没有好多了.
| 归档时间: |
|
| 查看次数: |
419 次 |
| 最近记录: |