【问题标题】:Cleanest way to create instances of class dynamically动态创建类实例的最简洁方法
【发布时间】:2020-04-20 13:04:21
【问题描述】:

在 calculations.py 中,我有一个名为 PowerPlant() 的类,带有

def __init__(self, parameter1, parameter2, parameter3, ...) 

以及属于该类的一些函数,例如计算供应(自我,变量1,变量2)。

我想将calculation.py 中的计算应用到一些存储在csv 文件中的发电厂。到目前为止,我使用以下方式...

在 Simulation.py 中,我使用 pd.read_csv() 从 csv 读取数据

plant_data = pd.read_csv('plants.csv', sep = ';', index_col = False, encoding = 'latin') 

然后我创建一个列表列表

# Create list of lists from plant_data DataFrame
list_of_plants = [list(row) for row in plant_data.values]

之后我用

创建了 PowerPlant 类的实例
## Outer loop: Iterate over all plants
for row in range(len(list_of_plants)):

    ElectricityOut = []
    Gains = []
    ...

    # Initialise an instance of the plant
    MyPowerPlant = PowerPlant(parameter1 = list_of_plants[row][0], 
                              parameter2 = list_of_plants[row][1], 
                              parameter3 = list_of_plants[row][2], 
                              ...)

    # call some methods from calculations.py 
    ...

有什么想法和建议可以让我以更好、更专业的方式做到这一点吗?
也许为每个植物创建一个对象?

【问题讨论】:

    标签: python list loops dataframe instance


    【解决方案1】:

    你可以像这样遍历一个列表,不需要 range(len())

    for row in list_of_plants:
    
        ElectricityOut = []
        Gains = []
        ...
    
        # Initialise an instance of the plant
        MyPowerPlant = PowerPlant(parameter1 = row[0], 
                                  parameter2 = row[0], 
                                  parameter3 = row[0], 
                                  ...)
    

    【讨论】:

    • 谢谢提示,我改了。
    【解决方案2】:

    我不喜欢使用 [item] 访问列表项,例如 list_of_plants[行][0]

    据我所知,不可能通过名称访问列表(为此使用字典),但是 namedTuples 是什么? 是否可以从 namedTuples 创建类的实例?如果是这样,我会将列表更改为 namedTuple...

    有什么建议吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-22
      • 2017-05-21
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 2020-04-15
      • 2014-05-25
      相关资源
      最近更新 更多