【问题标题】:Generating new object instances with different properties in Python在 Python 中生成具有不同属性的新对象实例
【发布时间】:2018-04-13 14:22:28
【问题描述】:

好的。我正在建立一个模型来描述一些管理决策对森林的影响。每个森林都是森林类的一个实例,您可以在下面看到一个简化版本:

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 等)输入数据并使用它来建立不同对象的清单?

对不起,如果这是一个愚蠢的问题(众所周知,我不时会问他们),但这真的让我很困惑。

【问题讨论】:

  • 属性存储在哪里?好像有4个。因此,您是否有一个列表列表[每个内部列表有 4 个项目]?还是发电机?
  • 在这个例子中有 4 个 - 都被剥离了,但可能还有很多其他的。我还没有将它们全部添加,所以我可以以任何最有效的格式制作它们。最终,我可能需要为启动条件使用某种形式的配置文件 - 但这还有一段路要走。
  • 好的,我想你的问题应该归结为将配置文件读入列表、字典或其他格式的列表。然后使用列表推导。

标签: python python-3.x oop


【解决方案1】:

如果您将属性存储在列表列表中,这是一种方法:

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

【讨论】:

  • 谢谢,这看起来像我所追求的,快速提出几个问题:forests = [Forest(*p) for p in properties] *p 在做什么?另外,为什么class Forest(object):中需要object
  • @Will *p 称为参数解包。它需要一些可迭代的并将其解包以填充参数。所以Forest(*[1, 2, 3, 4])在解包后变成Forest(1, 2, 3, 4)object 是老式/Python 2 声明类的方式(因为每个类都是 object 类的子类)。在 Python 3 中,您可以省略它而只使用 class Forest:,但包含它不会造成任何伤害。
  • @PatrickHaugh 实际上,在 Python 2 中,每个类都不是 object 的子类,除非你像这样特别要求它(而且你没有得到一些现代的没有它的功能);在 Python 3 中,每个类都是 object 的子类(具有所有额外功能),因此您无需再指定它。
  • @Will 这个答案的好处是,如果properties 是带有键wxyz 的字典列表,则相同的代码将起作用只需将* 更改为**,并且存储在 JSON、YAML 或 CSV 配置文件中的 dict 是使它们易于阅读和编辑的好方法,因此这为您提供了成长的空间任何你想要的设计。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
  • 2021-09-24
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多