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?
.method" on all instances. The parametermethodis never used.methodthen maybe it wasn't clear I wanted to call the instances method.my_function. What is preventing you from just callinginstance.do_something()on each element of the list (other than the method definition being wrong)?my_function.my_functionto call.do_something()on each instance? Do you want something else?