Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

python - Using parent class to contain many instances of child class

I am trying to write a data processing script and I think I'm misinterpreting the structure of Object Oriented Programming in Python.

I have sets of simulations that keep some variables constant and others which change according to the sim. I'm trying to contain the set of sims in a parent object and include a list of sims as an attribute, which are defined as a child object:

class Sim_set(path) :
    def __init__ :
        f = open(path)
        self.fixed_attributes = fixed_attributes(f)
        sims = [Sim(data) for data in f]

class Sim(Sim_set) :
    def __init__(data) :
        Sim_set.__init__()
        self.variable_attributes = variable_attributes(data)

    def derived_attributes() :
        self.derived_attributes = math(self.variable_attributes,self.fixed_attributes)

The problem is that it looks like for each Sim, a new instance of Sim_set is created, when in reality I want the opposite: I want a single instance of Sim_set, with attributes that Sim can fetch, and many instances of Sim, contained in Sim_set.

I apologize if this is a rather broad question, but am I doing this right?

EDIT: So based on the answers so far, what I'm doing now is:

So what I am doing now is :

class Sim :
    def __init__(data,sim_set) :
        self.sim_set = sim_set
        self.var_attr = f(data)

    def deriv_attr() :
        self.deriv_attr = g(self.var_attr,self.sim_set.fixed_attr)

It seems to work, but the crux of the question is really, "is this a good habit to have"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, Sim_set represents a set of simulations, and Sim represents of single simulation. It seems weird to me that a simulation inherits from a set of simulations.

I would break the parent-child relationship between Sim and Sim_set. Sim_set can still contain a collection of Sims but I don't think the parent-child relationship is appropriate here. Instead, I might add a new object, let's call it "Simluation_Lab" which is responsible for creating Sims and Sim_sets, and then populating them with the correct values.

You might also want to read up on Dependency Injection, it might help in this situation: https://medium.com/@shivama205/dependency-injection-python-cb2b5f336dce


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...