如果我理解正确,您需要字典工厂模式
>>> class Calc(object):
def __init__(self):
#Initialize a dictionary of keywords and callbacks
self.operation = {
'add':self.add,
'sub':self.sub,
'mul':self.mul,
'div':self.div,
'neg':self.neg
}
#Overload the function call
def __call__(self, *args):
return self.operation[args[0]](*args[1:])
# *args - variable list argument list
def add(self,*args):
return sum(args)
def sub(self,*args):
return args[1] - args[0]
def mul(self, *args):
if len(args) == 0:
return 1
elif len(args) == 1:
return args[0]
else:
return args[0] * args[1]
def div(self, *args):
return args[0] / args[1]
def neg(self, *args):
return -args[0]
>>> calc = Calc()
>>> calc('add',1,2,3)
6
>>> calc('mul',10)
10
>>> calc('mul',10,4)
40
>>> calc('neg',3)
-3
>>>