How to make classes with multi-level functions?

Asked

Viewed 30 times

-1

I’m developing a code for the following problem: I have a series of experiments to be done. For each experiment, I have to do different calculations (which I called beta, dynamic and static in the example below) and plot different graphs.

Naturally, I thought I’d do something like this:

class experiment:
    
    def __init__(self,a,b,c):
        
        self.a=a
        self.b=b
        self.c=c
        
    def beta(self):
        
        def calculate(self):
            
            return self.a+self.b
        
        def plot(self):
            pass
        
    def static(self):
        
        def calculate(self):
            
            return self.a+self.b+self.c
        
        def plot(self):
            pass
        
    def dinamic(self):
        
        def calculate(self):
            
            return self.a+self.b*self.c
        
        def plot(self):
            pass        

My goal is that it was possible to call the function with a command like exp.beta.calculate() and exp.dinamic.plot(), for example, but it is not working as I wanted. This way as I did gives the following errors:

teste.beta.calculate()
AttributeError: 'function' object has no attribute 'calculate'

teste.beta().calculate()
AttributeError: 'NoneType' object has no attribute 'calculate'

The question is: how do I get to write code that have multiple levels like the ones I’m trying to?

P.S.: I have tried to do using multiple inheritance but it also does not work the way I intend, because I would have to be instantiating the same experiment several times.

P.P.S.: Sorry if the title was inappropriate, but I have no idea of the "technical name" for this question.

Thank you.

1 answer

1


I’m not reproducing everything that’s in your example, but I think you can get an idea.

Defining Beta

>>> class Beta:
...     def __init__(self, a, b):
...         self.a = a
...         self.b = b
...     def calculate(self):
...         return self.a + self.b

Definindo Experiment

>>> class Experiment:
...     def __init__(self, a, b, c):
...         self.a = a
...         self.b = b
...         self.c = c
...         self.beta = Beta(self.a, self.b)
...

Running

>>> e = Experiment(1,2,3)

>>> e.beta.calculate()
3
  • that’s exactly what I wanted. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.