我有一个 Python 类,需要根据条件在两种方法之间动态选择。两种方法都带有参数。我想使用一个属性来确定要调用哪个方法。我怎样才能实现这个目标?
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'
如何实现方法属性来实现此行为?
只需从您的
method
属性返回正确的方法即可。 (它会自动绑定到同一个 self
实例,所以你不需要担心类似的事情。)
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")
打印出来
<__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'