Search code examples
python-3.xclassmethodsgetattr

Using getattr() on self


I have a class and within one of the methods of the class I have a string given from user input which is then mapped to the corresponding method (technically is a str representation of the method). How can I call this method without an instance of the class being created yet, i.e., with self. argument. I've included what I thought would work but it doesn't...

class RunTest():
      def __init__(self, method_name):
          self.method_name = method_name #i.e., method_name = 'Method 1'

      def initialize_test(self):
          mapping = {'Method 1': 'method1()', 'Method 2': 'method2()', ...}
          test_to_run = getattr(self, mapping[self.method_name])

      def method1(self):
          ....

      def method2(self):
          ....

Solution

  • If i understand correctly you would like to map your classes attribute to a method based on user input. This should do what you want it to:

    class YourClass:
        def __init__(self, method_name):
            mapping = {'Method 1': self.method_one,
                        'Method 2': self.method_two}
    
            self.chosen_method = mapping[method_name]
    
        def method_one(self):
            print('method one')
    
        def method_two(self):
            print('method two')
    
    while True:
        name = input("enter 'Method 1' or 'Method 2'")
        if name != 'Method 1' and name != 'Method 2':
            print('Invalid entry')
        else:
            break
    
    your_class = YourClass(name)
    your_class.chosen_method()
    

    This avoids needing to use getattr() at all. Make sure that in your mapping dictionary you do not have parenthesis on the methods (ex. {'Method 1': self.method_one()...). If you do then chosen_method will equal whatever that method returns.