Search code examples
pythonfunctionoopscipybisection

How do I access methods/attributes of one object to use in another object in Python?


I have two objects below:

class foo1:
    def __init__(self,value):
        self.value = value
    def calc(self):
        return self.value**2

class foo2:
    def __init__(self,value):
        self.value = value
    def calc(self):
        return self.value**3

I am planning on doing a bisection method function (whether using scipy.optimize or not). However, the function I need to evaluate the bisection method on is foo1.calc(value) - foo2.calc(value) = 0.

I am relatively new to Python/OOP - is there a way to access these methods in a function/object, i.e. to do something equivalent to:

def func(value):
    return foo1.calc(value) - foo2.calc(value)

I have considered using multi-class inheritance of foo1 and foo2 but I was wondering if there is a simpler way to do this.


Solution

  • The way you use classes like this:

    f1 = foo1(10)
    f2 = foo2(3)
    result = f1.calc() - f2.calc()