gpt4 book ai didi

python - 如何在 Python 上实现一个既可以接受内置类型又可以接受自定义类的函数?

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:44 25 4
gpt4 key购买 nike

我想创建一个库来计算具有未知变量的表达式。为此,我做了这样的事情。

A = Forward() # Syntax from pyparsing
C = Forward()
B = A * 4 + C # B has Expr type.
A << 4
C << 4
# B can be evaluated to value 20 now
D = 8

print(Evaluate(B)) # should print 20
print(Evaluate(A)) # should print 4
print(Evaluate(D)) # should print 8

我想让 Evaluate 函数接受 int、Forward、Expr 和更多类型。由于 int 类型不能有自定义方法,简单的鸭子类型似乎不起作用。

还有比这更 pythonic 的吗?

def Evaluate(x):
if isinstance(x, int):
return x
else:
return x.Evaluate() # Forward, Expr has Evaluate method.

最佳答案

如果您所有的自定义类都实现了.Evaluate,您可以这样做

try:
return x.Evaluate()
except AttributeError:
return x

关于python - 如何在 Python 上实现一个既可以接受内置类型又可以接受自定义类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153141/

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