【问题标题】:Use keywords in class to call a specific method在类中使用关键字来调用特定的方法
【发布时间】:2016-03-31 09:04:50
【问题描述】:

假设一个Python类有不同的方法,根据用户指定的不同,在主函数calculate()中执行不同的方法。

在下面的示例中,用户需要指定关键字参数'methodOne''methodTwo'。如果没有指定或指定了不正确的关键字,则默认为'methodOne'

class someClass(object):
    def __init__(self,method=None):
        methodList = ['methodOne','methodTwo']
        if method in methodList:
            self.chosenMethod = method
        else:
            self.chosenMethod = self.methodOne

    def methodOne(self):
        return 1

    def methodTwo(self):
        return 2

    def calculate(self):
        return self.chosenMethod()

上面显然不起作用,因为method 是一个字符串而不是一个函数。如何根据我的关键字参数method 选择self.methedOne()self.methedOne()?原则上,以下工作:

def __init__(self,method=None):
    if method == 'methodOne':
        self.chosenMethod = self.methodOne
    elif method == 'methodTwo':
        self.chosenMethod = self.methodTwo
    else:
        self.chosenMethod = self.methodOne

但如果我有两个以上的方法,这会变得相当难看。有没有办法做到这一点类似于我的原始代码?

【问题讨论】:

  • 下面的答案已经显示了getattr的使用。这种方法称为反射(或自省):检查自身结构的代码。但是,请记住,如果 method 是用户提供的值,您最好验证它是否引用了预期的方法之一。毕竟,用户可以输入'calculate',或'__class__',或不可调用属性的名称,从而导致各种问题(甚至可能是安全风险,具体取决于上下文)。
  • @PieterWitvoet if method in methodList 子句应该防止这种情况发生。
  • @Forzaa:很好。 :)

标签: python class methods keyword


【解决方案1】:

您可以为此使用getattr()

class someClass(object):
    def __init__(self,method=None):
        methodList = ['methodOne','methodTwo']
        if method in methodList:
            self.chosenMethod = method
        else:
            self.chosenMethod = self.methodOne

    def methodOne(self):
        return 1

    def methodTwo(self):
        return 2

    def calculate(self):
        return getattr(self, self.chosenMethod)()

x = someClass(method='methodOne')
print x.calculate()
>>> 1

【讨论】:

  • 嗯,两个几乎相同的答案同时出现。猜猜这是这样的:)。我会接受你的,因为它更符合我的代码。
【解决方案2】:

您可以使用getattr 来获取类对象上的实际方法。

class someClass(object):
    def __init__(self,method=None):
        # store it with the object so we can access it later in calculate method
        self.method = method

    def methodOne(self):
        return 1

    def methodTwo(self):
        return 2

    def calculate(self):
        # get the actual method from the string here
        # if no such method exists then use methodOne instead
        return getattr(self, self.method, self.methodOne)()


> someClass('methodOne').calculate()
# 1

> someClass('methodTwo').calculate()
# 2

【讨论】:

  • 对于默认情况的处理,您可以添加getattr(self, self.method, self.methodOne)()
猜你喜欢
  • 2023-03-21
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多