Reputation: 17342
This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?
class Example:
def __init__(self, parameter):
if parameter == 0:
# trivial case, the result is always zero
self.calc = lambda x: 0.0 # <== replacing a method
self._parameter = parameter
def calc(self, x):
# ... long calculation of result ...
return result
(If there is any difference between Python2 and Python3, I'm using Python3 only.)
Upvotes: 1
Views: 110
Reputation: 696
You'll have a problem should parameter
ever changes, so I don't consider it good practice.
Instead, I think you should do this:
class Example:
def __init__(self, parameter):
self._parameter = parameter
def calc(self, x):
if not self._parameter:
return 0.0
# ... long calculation of result ...
return result
Upvotes: 3
Reputation: 17342
I decided to post a summary of several comments and answers. Please do not vote for this summary, but give +1 to the original authors instead.
__methods__
if cond: return 0.0
for simple cases: class Example:
def __init__(self, parameter):
if parameter == 0:
self.calc = self._calc_trivial
else:
# ... pre-compute data if necessary ...
self.calc = self._calc_regular
self._parameter = parameter
def _calc_regular(self, x):
# ... long calculation of result ...
return result
@staticmethod
def _calc_trivial(x):
return 0.0
Upvotes: 0
Reputation: 4265
This is very confusing. If someone else reads it, they won't understand what is going on. Just put a if
statement at the beginning of your method.
def calc(self, x):
if self.parameter == 0:
return 0
# ... long calculation of result ...
return result
Also if you change self.parameter
after it was initialized with 0
, your function wouldn't work anymore.
Upvotes: 4