Suppose a class myClass
has two method definitions _call1
and _call2
, but only one of them should be used depending on a parameter passed when the object is instantiated, and a specific alias call
is given for the chosen method. How to program this? A minimum example is shown below.
The reason behind this code is that I would like to avoid the overhead of having an if-else
statement with two possible return
s inside a single call
method. Another option would be to create two different possible classes based on cond_param
, but I'd rather avoid that.
class myClass:
def __init__(self, cond_param):
self.cond_param = cond_param
# depending on the value of the conditional parameter `cond_param`,
# a method named `call` will be assigned to one of the methods
# defined below
if self.cond_param not in [1, 2]:
return ValueError
if self.cond_param == 1:
call = _call1
else
call = _call2
def _call1(self):
return "call 1!"
def _call2(self):
return "call 2!"
obj1 = myClass(1)
print(obj1.call()) # should print "call 1!"
obj2 = myClass(2)
print(obj2.call()) # should print "call 2!"