0

A functional example (out of class) for a better explanation about what I'm trying to get.

def greet():
   print('Hello world')

func = 'greet'
func()

But, if I use same example as a class method, I cannot get the same result. I understand Python is looking for a class method called "func", but I don't know (if is possible to do it), tell to Python that "c.func()" is "c.greet()" really.

class MyApp:

   def greet(self):
     print('Hello world')

func = 'greet'

c = MyApp()
c.func()
Carlos Diaz
  • 321
  • 1
  • 15
  • 1
    Um, `func()` in your first example would raise a `TypeError`, because `str` objects are not callable, and you assigned a `str` object to func. In any case, to dynamically access attributes, use `getattr(obj, attribute)` where `attribute` is a string. So, in your case, you want `getattr(c, func)()` – juanpa.arrivillaga Aug 21 '20 at 10:08
  • Many thanks for your explanation @juanpa.arrivillaga – Carlos Diaz Aug 21 '20 at 10:26

0 Answers0