python call class method by name code example

Example 1: python execute function from string

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

Example 2: python call function in class

#------------------------------------
#CLASS
#------------------------------------
class Student:
  def __init__(self):
    self.name = None
    
  def set_name(self, word):
    self.name = word
    return self.get_name()
    
  def get_name(self):
    return self.name
  
#------------------------------------
# USAGE:
#------------------------------------

a = Student()
print(a.set_name("Hello"))

Example 3: python get function from string name

module = __import__('foo')
func = getattr(module, 'bar')
func()