I have a Python class that needs to dynamically choose between two methods based on a condition. Both methods take parameters. I want to use a property to determine which method to call. How can I achieve this?
class MyClass:
def __init__(self, condition):
self.condition = condition
def _method_1(self, param1, param2):
# Implementation for the first add_way method
print(f"_method_1 called with {param1} and {param2}")
def _method_2(self, param1, param2):
# Implementation for the second add_way method
print(f"_method_2 called with {param1} and {param2}")
@property
def method(self):
# How to return the correct method based on self.condition?
pass
# Example usage:
manager = WayManager(condition=True)
manager.method('value1', 'value2') # Should call _method_1 with 'value1' and 'value2'
manager.condition = False
manager.method('value3', 'value4') # Should call _method_2 with 'value3' and 'value4'
How can I implement the method property to achieve this behavior?
Simply return the correct method from your method
property. (It will be bound to the same self
instance automatically, so you don't need to worry about anything like that.)
class MyClass:
def __init__(self, condition):
self.condition = condition
def _method_1(self, param1, param2):
print(f"{self}._method_1 called with {param1=} and {param2=}")
def _method_2(self, param1, param2):
print(f"{self}._method_2 called with {param1=} and {param2=}")
@property
def method(self):
return self._method_1 if self.condition else self._method_2
manager = MyClass(condition=True)
manager.method("value1", "value2")
manager.condition = False
manager.method("value3", "value4")
prints out
<__main__.MyClass object at 0x1031c91f0>._method_1 called with param1='value1' and param2='value2'
<__main__.MyClass object at 0x1031c91f0>._method_2 called with param1='value3' and param2='value4'