How to dynamically call methods within a class using method-name assignment to a variable
Question:
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function' + self.i
self.func_name() # <-- this does NOT work.
def function1(self):
pass # do something
def function2(self):
pass # do something
This gives the error: TypeError: 'str' object is not callable
How would I go about doing this?
Note: self.func_name
also does not work
Answers:
def get(self):
def func_not_found(): # just in case we dont have the function
print 'No Function '+self.i+' Found!'
func_name = 'function' + self.i
func = getattr(self,func_name,func_not_found)
func() # <-- this should work!
Two things:
-
In line 8 use,
func_name = ‘function’ + str(self.i)
-
Define a string to function mapping as,
self.func_options = {'function1': self.function1,
'function2': self.function2
}
-
So it should look as:
class MyClass:
def __init__(self, i):
self.i = i
self.func_options = {'function1': self.function1,
'function2': self.function2
}
def get(self):
func_name = 'function' + str(self.i)
func = self.func_options[func_name]
func() # <-- this does NOT work.
def function1(self):
//do something
def function2(self):
//do something
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function' + self.i
self.func_name() # <-- this does NOT work.
def function1(self):
pass # do something
def function2(self):
pass # do something
This gives the error: TypeError: 'str' object is not callable
How would I go about doing this?
Note: self.func_name
also does not work
def get(self):
def func_not_found(): # just in case we dont have the function
print 'No Function '+self.i+' Found!'
func_name = 'function' + self.i
func = getattr(self,func_name,func_not_found)
func() # <-- this should work!
Two things:
-
In line 8 use,
func_name = ‘function’ + str(self.i)
-
Define a string to function mapping as,
self.func_options = {'function1': self.function1, 'function2': self.function2 }
-
So it should look as:
class MyClass:
def __init__(self, i): self.i = i self.func_options = {'function1': self.function1, 'function2': self.function2 } def get(self): func_name = 'function' + str(self.i) func = self.func_options[func_name] func() # <-- this does NOT work. def function1(self): //do something def function2(self): //do something