VPfB
VPfB

Reputation: 17342

Is it OK to replace a method by a plain function?

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

Answers (3)

Quan To
Quan To

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

VPfB
VPfB

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.

  • the approach is safe except for special __methods__
  • the approach is deemed unpythonic, undesirable, or unnecessary etc.
  • the parameter determining the function to use must be constant. If it is not the case, this approach makes no sense at all.
  • from several suggestions I prefer the code below for general cases and the obvious 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

Saeid
Saeid

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

Related Questions