python 2.7 - AttributeError: instance has no attribute 'function' -
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)
then
>>>f0=f() >>>f0.f3(1)
the error is:
"attributeerror: f instance has no attribute 'function'"
how can fix if still wanna f3() select function of f1 or f2 in class?
you can use .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)
usage:
f0 = f() print(f0.f3(1)) # prints 1 print(f0.f3(1, "f2")) # prints 2.0
Comments
Post a Comment