行。我正在建立一个模型,描述一些管理决策对森林的影响。每个林都是林类的一个实例,您可以在下面看到简化版本:
class forest():
instancelist = [] # a list of all the forest instances so I can run functions on all of them at once
growth_rate = 2 #very simple rate of growth (not realistic!)
felling_year = 50 #all forest areas are felled at age 50
def __init__(self, x=0, y=0,age=0,size=0):
self.instancelist.append(self) # add the forest area to the instance list
self.x = x # x coordinate
self.y = y # y coordinate
self.age = age # age, not all forests are planted on bare sites, - we have some pre-existing ones to consider.
self.size = size # very rough - but this is an indicator of the physical volume of timber (not area)
我现在可以生成一个林对象,例如:
f = forest(1,1,20,40)
所以,我遇到的困难是我需要生成一些森林块(所以我们看到效果在更广泛的区域)。要做到这一点,我需要创建很多领域。
如果我没有指定任何属性,我可以轻松地做到这一点:
forests = [forest() for x in range(20)]
但我无法看到如何生成大量具有独特属性的区域,而无需通过手动指定它们。是否有一种方法可以用于从其他来源(列表,元组,csv等)提供数据并使用它来构建不同对象的清单?
很抱歉,如果这是一个愚蠢的问题(我不时会问他们),但这让我很困惑。
答案 0 :(得分:2)
如果您将属性存储在列表列表中,这是一种方法:
class Forest(object):
def __init__(self, w, x, y, z):
self.w = w
self.x = x
self.y = y
self.z = z
return None
properties = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]]
forests = [Forest(*p) for p in properties]
print(forests[1].x) # 6