在自身上使用getattr()

问题描述 投票:-1回答:1

我有一个类,并且在该类的一种方法中,我有一个由用户输入提供的字符串,该字符串随后被映射到相应的方法(技术上是该方法的str表示形式)。我如何在尚未创建类实例(即使用self)的情况下调用此方法。论点。我已经包含了我认为会起作用的内容,但是没有用...

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):
          ....
python-3.x class methods getattr
1个回答
0
投票

如果我正确理解,您希望将您的classes属性映射到基于用户输入的方法。这应该做您想要的:

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()

这完全避免了使用getattr()。确保在映射字典中,方法上没有括号(例如{'Method 1': self.method_one()...)。如果这样做,则chosen_method将等于该方法返回的值。

© www.soinside.com 2019 - 2024. All rights reserved.