Search code examples
pythonclassmethods

Class instantiation and bound funcitons


I'm using a package that defines a class Test with the following snippet of code.

if self.accept(proposed_next_state):
    self.state = proposed_next_state

and the __init__ function sets self.accept in the following simple way

def __init__(self, accept,initial_state):
        self.accept = accept
        self.state = initial_state

I'm trying to define a function func for accept that can use both proposed_next_state and self.state. The problem is that if I define an instance of the class as

instance=Test(func,initial_state)

then func cannot access self.state because it is not bound to Test. What's the easiest way to do this?

The workaround I have right now is by extending the class in the following way

def extendedTest(Test):
    def func(self, proposed_next_state):
       #do stuff here

instance=extendedTest(func,initial_state)
instance.accept=instance.func

but this seems like a hack. Is there a better way to do this?


Solution

  • Modifying attributes of an instance after instantiation does feel a bit hacky. You can override __init__ instead and make it pass self.func as accept to the parent method:

    def extendedTest(Test):
        def __init__(self, initial_state):
            super().__init__(self.func, initial_state)
    
        def func(self, proposed_next_state):
            #do stuff here
    
    instance = extendedTest(initial_state)