在类定义中声明允许的实例变量?

问题描述 投票:0回答:0

我正在寻找使用类对象来存储来自多个模拟的数据并将它们保存在列表中,列表中的每个条目都是该类的一个新实例)。我想确保每个实例都具有完全相同的属性(变量),但希望在程序运行时动态分配它们——而不是在创建新实例时同时分配所有这些属性。

这样做的一些建议(我在 C 中使用结构)是here,但是如果使用本机类(为了简单/可读性,首选选项而不是外部模块或字典),我看不到一种方法以确保每个实例都具有完全相同的属性,但它们是在不同时间填充的。请告诉我是否有解决方案。

不想使用下面的构造函数,因为所有属性都必须立即填充 - 那么我想我必须在模拟结束时创建对象,但必须确定额外的变量来存储数据同时。这也不是很好,因为我有大量的属性,括号中的参数会很长。

simulations = []

class output_data_class:

    def __init__(self, variable1, variable2):
        
        self.variable1 = variable1
        self.variable2 = variable2
        
        
# simulation, generates the data to store in variable1, variable2

variable1 = 'something' # want to avoid these interim variables
variable2 = 123 # want to avoid these interim variables

new_simulation = output_data_class(variable1, variable2) # create an object for the current simulation

simulations.append(new_simulation) # store the current simulation in the list

现在我正在使用这样的东西:

simulations = []

class output_data_class:

    pass
        


new_simulation = output_data_class() # create an object for the current simulation


        
# simulation, generates the data to store in variable1

new_simulation.variable1 = 'something'

# another part of simulation, generates the data to store in variable2

new_simulation.variable2 = 123 

simulations.append(new_simulation) # store data from current simulation

这允许我添加在模拟过程中产生的数据(可以是数据数组,然后是从该数组计算出的东西等)。我的直觉是以上是不好的做法 - 它不是立即清楚实例属性应该是什么,并且它不能防止由于拼写错误等而创建全新的属性(下面的示例)。我想强制每个实例必须具有相同的属性。

new_simulation.variabel2 = 123 

注意上面的拼写错误 - 这会专门为此实例创建一个新变量,对吗?

我希望能够在类定义中声明可接受的属性(如果可能的话包括它们的类型),但显然不是类变量,因为我需要为每个实例单独填充它们。 (重申一下,不是在 innit 方法中,因为那时我相信我必须一次填充所有属性。)

非常感谢您的任何建议!

-亨利

python class instance instance-variables class-variables
© www.soinside.com 2019 - 2024. All rights reserved.