【问题标题】:Using getattr() on self对自己使用 getattr()
【发布时间】:2019-09-27 23:14:28
【问题描述】:

我有一个类,并且在该类的一个方法中,我有一个从用户输入给出的字符串,然后将其映射到相应的方法(技术上是该方法的 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):
          ....

【问题讨论】:

  • 你想调用什么方法?它属于类吗?
  • 根据字符串method_name,它将是上面代码中的method1() 或method2() 之一。所以,回答你的第二个问题,是的,它属于类
  • 如何在不启动类的情况下设置method_name?它是在创建实例时设置的。
  • 对不起,我是 python 新手......所以你不能让一个方法依赖于另一个?
  • 其实我知道只要有 self.method(),你就可以在另一个方法中调用它。我想做同样的事情,除了这个方法是字符串格式的。我想拿走字符串,让它像 self.method1() (或 self.method2())一样工作

标签: python-3.x class methods getattr


【解决方案1】:

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

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 将等于该方法返回的任何内容。

【讨论】:

  • 非常感谢!这行得通!除了删除字典中的括号外,这重新组合了我的其他方法。为什么python还能识别函数,但是去掉括号后不调用呢?
  • 是的,引号也被删除,因此它不是字符串。如果您将其保存为字符串,则必须使用不同的方法来访问它。当您放置括号时,它会运行该函数。所以无论函数返回什么都是你的键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
相关资源
最近更新 更多