在类中使用关键字来调用特定的方法

2024-06-30 07:52:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设一个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

但如果我有两种以上的方法,这会变得相当丑陋。有没有类似于我的原始代码的方法


Tags: 方法函数用户selfnone参数returninit
2条回答

为此,您可以使用^{}

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

可以使用^{}获取类对象上的实际方法

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

相关问题 更多 >