Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class taking in instance as argument

Tags:

python

I have the following class:

class Optimization_problem():
    def __init__(self, **args):
        if 'function' in args:  
            self.function = args['function']
        if 'gradient' in args:  
            self.gradient = args['gradient']
        else:
            def deriv(x):
                return nd.Gradient(self.function)(x)
            self.gradient= deriv

        if 'acc' in args:  
            self.acc = args['acc']

I want to create a class Optmization_method which inherits the attributes from the class above in such a way that i can do the following:

f = lambda x: 100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2
problem = Optimization_problem(function=f, acc=1.e-3)
method = Optimization_method(problem) # I want to be able to do this

I have tried the following but it doesn't work.

class Optimization_method(Optimization_problem):    
    def __init__(self, **args):
        Optimization_problem.__init__(self, **args)

    #methods......
like image 344
JustANoob Avatar asked Jul 16 '26 13:07

JustANoob


1 Answers

You are just passing in a simple single argument. If you want to copy attributes across, you'd have to specifically look for such an instance and copy out the data you want. That can be as simple as copying the __dict__ mapping:

if len(args) == 1 and isinstance(args[0], Optimization_problem):
    self.__dict__.update(args[0].__dict__)
    return

Note that this has nothing to do with inheritance; inheritance doesn't give you the ability to copy state (data) from a base class, it gives you the ability to reuse and extend functionality.

If you wanted to reuse the attributes of a specific instance, just store a reference to instance, a concept called composition:

class Optimization_method:    
    def __init__(self, problem):
        self.problem = problem

    def method1(self,x):
        return self.problem.function(x)

Only use inheritance if you want Optimization_method instances to support the same operations as Optimization_problem. Use composition if you want to be able to reference the state and functionality of another instance for what the current class needs to achieve.

like image 64
Martijn Pieters Avatar answered Jul 18 '26 02:07

Martijn Pieters