class operate(object):
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def multi(self):
return self.a * self.b
def main(a, b, method):
Oper = operate(a, b)
method_dict = {
"add":Oper.add(), "multi":Oper.multi()}
res = method_dict[method]
return res
if __name__ == "__main__":
res1 = main(2, 3, "multi")
res2 = main(2, 3, "add")
print(res1, res2)
输出:
6 5
其实就是 字典 代替很多的 if...else...