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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With