class f:
def f1(self, x):
return x
def f2(self, x):
return 2.0*x
def f3(self, x, function=f1):
return self.function(x)
然后
>>>f0=f()
>>>f0.f3(1)
错误是:
"AttributeError: f instance has no attribute 'function'"
如果我仍然希望f3()在这个类中选择f1或f2的函数,我该怎么办呢?
答案 0 :(得分:0)
您可以使用.getattr()
:
class f:
def f1(self, x):
return x
def f2(self, x):
return 2.0 * x
def f3(self, x, function="f1"):
return getattr(self, function)(x)
用法:
f0 = f()
print(f0.f3(1)) # prints 1
print(f0.f3(1, "f2")) # prints 2.0