gpt4 book ai didi

python - 引用纯虚方法

转载 作者:行者123 更新时间:2023-12-01 08:12:34 26 4
gpt4 key购买 nike

我可能在这里遗漏了一些明显的东西。我有一个简单的类层次结构,大致如下所示:

class Any:
def op2_additive_add(self, other: 'Any') -> 'Any':
raise NotImplementedError

def op2_multiplicative_multiply(self, other: 'Any') -> 'Any':
raise NotImplementedError

def op2_exponential_power(self, other: 'Any') -> 'Any':
raise NotImplementedError

# A dozen of similar methods not shown

class Rational(Any):
def op2_additive_add(self, other: 'Any') -> 'Rational':
pass # Implementation not shown

def op2_multiplicative_multiply(self, other: 'Any') -> 'Rational':
pass # Implementation not shown

def op2_exponential_power(self, other: 'Any') -> 'Rational':
pass # Implementation not shown

class Set(Any):
def op2_additive_add(self, other: 'Any') -> 'Set':
pass # Implementation not shown

def op2_multiplicative_multiply(self, other: 'Any') -> 'Set':
pass # Implementation not shown

def op2_exponential_power(self, other: 'Any') -> 'Set':
pass # Implementation not shown

# Half a dozen of similar derived types not shown.

我正在实现一个调度程序类,该类应该在不知道两个操作数类型的情况下选择所请求的操作,并将对正确方法的引用传递给执行程序。大致是这样的(下面的代码不起作用):

def select_operator(selector) -> typing.Callable[[Any, Any], Any]:
if selector.such_and_such():
return Any.op2_additive_add
elif selector.so_and_so():
return Any.op2_exponential_power
# And so on

上面的代码将不起作用,因为尝试调用返回的未绑定(bind)方法将绕过动态调度;即 select_operator(selector)(foo, bar) 将始终抛出 NotImplementedError

到目前为止我能想到的最好的解决方案大致是这样的,但它并不漂亮:

def select_operator(selector) -> str:
if selector.such_and_such():
return Any.op2_additive_add.__name__
elif selector.so_and_so():
return Any.op2_exponential_power.__name__
# And so on

method_name = select_operator(selector)
getattr(foo, method_name)(bar)

TL;DR:如何将动态分派(dispatch)过程延迟到我引用某个方法之后?

最佳答案

也许这样会更合适?

class Any:
def select_and_do_op(self, selector, other):
if selector.such_and_such():
return self.op2_additive_add.(other)
elif selector.so_and_so():
return self.op2_exponential_power(other)
...

foo.select_and_do_op(selector, bar)

更新

另一种解决方案:

def select_operator(selector):
if selector.such_and_such():
return lambda foo, bar: foo.op2_additive_add(bar)
elif selector.so_and_so():
return lambda foo, bar: foo.op2_exponential_power(bar)
...

operator = select_operator(selector)
result = operator(foo, bar)

关于python - 引用纯虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55148139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com