Home > Enterprise >  Using a class method as an argument to a function
Using a class method as an argument to a function

Time:09-30

I want to pass an class method as an argument to a function which applies the method to an instance. I wrote a simplified example of my problem down, which does not work. Is there a way to do this in python?

class A:
    def __init__(self):
        self.values = [1,2,3]
        
    def combine(self) -> int:
        return sum(self.values)
    
    def return_zero(self) -> int:
        return 0
    

def apply_func(instance, func):
    return instance.func()


print(apply_func(A(), A.combine))

> AttributeError: 'A' object has no attribute 'func'
        

CodePudding user response:

You could use getattr():

def apply_func(instance, func):
    fn = getattr(instance, func)
    return fn()


print(apply_func(A(), 'combine'))

Out:

6

CodePudding user response:

Instead of

def apply_func(instance, func):
    return instance.func()

you should do:

def apply_func(instance, func):
    return func(instance)

Remember the method is defined as def combine(self) - by calling func(instance), the instance simply becomes that self.

Try it online!

  • Related