简体   繁体   中英

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. Since int types cannot have custom methods, simple duck typing don't seem to work.

Is there more pythonic one than this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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