Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a instance method as an argument without knowing the instance in Python

Tags:

python

I want to pass an instance method to another function but when I do I don't know from which instance that will be. I only know the base class from which those instances are derived. Is there a way to call the instance method from inside the function?

I have the following code:

class Base:
    def do_something():
        pass        


class InstanceOne(Base):
    def do_something():
        print("Instance One")


class InstanceTwo(Base):
    def do_something():
        print("Instance Two")


def my_function(instances_list: List[Base], method)
    for instance in instances_list:
        instance.method()


# The main part
my_list = [InstanceOne(), InstanceTwo(), InstanceTwo(), InstanceOne()]
my_function(my_list, Base.do_something)

The code above won't work because the function do_something is called on the Base class and not on the instances. Is there a way to actually call the instances's methods do_something when the function (my_function) doesn't know what the instances will be?

like image 299
Enzo Avatar asked Feb 04 '26 08:02

Enzo


1 Answers

You can use operator.methodcaller

def my_function(instances_list: List[Base], method_name):
    method = methodcaller(method_name)
    for instance in instances_list:
        method(instance)

Also your functions are methods, they need to accept a self argument.

Your code should look as follows:

from operator import methodcaller

class Base:
    def do_something(self):
        pass        


class InstanceOne(Base):
    def do_something(self):
        print("Instance One")


class InstanceTwo(Base):
    def do_something(self):
        print("Instance Two")


def my_function(instances_list, method_name):
    method = methodcaller(method_name)
    for instance in instances_list:
        method(instance)


# The main part
my_list = [InstanceOne(), InstanceTwo(), InstanceTwo(), InstanceOne()]
my_function(my_list, 'do_something')

This outputs:

Instance One
Instance Two
Instance Two
Instance One
like image 196
Jab Avatar answered Feb 05 '26 22:02

Jab