Search code examples
pythonpython-3.xselfinstance-methods

Python passing instance methods as arguments


I want to pass an instance method as an argument to a function that applies it to an instance it internally has. Is this possible in Python?


Solution

  • Python object methods are functions that expect the instance as their first parameter. Calling myInstance.method(x) is similar to calling type(myInstance).method(myinstance,x)

    An example of how this works can be seen when calling the map function.

    L = [ [1,2,3],[4,5],[6,7,8,9] ]
    
    print(*map(list.pop,L)) # 3 5 9
    
    print(L) # [[1, 2], [4], [6, 7, 8]]
    

    We passed a method of the list class as a parameter to map() which handles the lists in L internally. So the map() function is applying a method on list instances that it has internally.

    To do the same thing, you can define a method or function that expects a method as a parameter and add your object instance as the first parameter when calling it:

    def apply(method):
        myInstance = list()
        method(myInstance)