简体   繁体   English

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

[英]How to implement a function that can both accept built-in types and custom classes on Python?

I want to create a library for calculating expressions with unknown variables. 我想创建一个用于计算具有未知变量的表达式的库。 For doing this, I did something like this. 为此,我做了这样的事情。

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

I want to have Evaluate function accept int, Forward, Expr, and many more types. 我想让Evaluate函数接受int,Forward,Expr等更多类型。 Since int types cannot have custom methods, simple duck typing don't seem to work. 由于int类型不能具有自定义方法,因此简单的鸭子类型输入似乎无效。

Is there more pythonic one than this? 有比这更多的pythonic吗?

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

If all your custom classes implement .Evaluate , you could just do 如果所有自定义类都实现.Evaluate ,则可以执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM