0

I am attempting to call a class method by variable name that I extract from an external file, as seen below:

structures.py:

event_map = {'year' : 'get_year'}

Class code:

class MyClass(object):
    def __init__(self):
        self._analyze()

    def _analyze(self):
        event_method = event_map['year']
        self.event_method() #<--------------this doesn't work

    def get_year(self):
        print('here')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 'get_year' in your dict is a string, not a method. Also you set event_method but then use self.event_method. Also, event_map seems to be declared outside of your class, so it won't be aware of what `get_year` is. – JeffUK Dec 06 '20 at 00:55
  • Your example are strange and unclear, but you can try 'event_method(self)' on your real code, because in this example code event_method is a string and will not work. – Daniel Farina Dec 06 '20 at 00:59
  • https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string is what you really want I think – dpwr Dec 06 '20 at 01:01
  • "that I extract from an external file" what does this mean, exactly? – juanpa.arrivillaga Dec 06 '20 at 01:23

2 Answers2

2

You can use getattr to get an attribute by name:

getattr(self, event_method)()
B. Morris
  • 630
  • 3
  • 15
1

Python has a getattr(object, name) function to call a function given its name as a string. You would use getattr(self, event_method)():

lass MyClass(object):
    def __init__(self):
        self._analyze()

    def _analyze(self):
        event_method = event_map['year']
        getattr(self, event_method)()

    def get_year(self):
        print('here')
thshea
  • 1,048
  • 6
  • 18