1

您可以推迟代码执行:

In [12]: v = 5

In [13]: e = ' v * 2 '

In [14]: eval(e)
Out[14]: 10

我想对普通 python 代码进行后期评估而不将其分配给字符串?

有没有一种技术可以做到这一点?关闭? __call__?


另一个例子 :

In [15]: b = bitarray('10110')

In [16]: p = Pipe(lambda x : x * 2 )

In [17]: e = ' b | p '

In [18]: eval(e)
Out[18]: bitarray('1011010110')

我正在尝试构建类似于 TensorFlow 和 keras 的执行流程的图表/管道,然后传递数据并收集结果......它比这更复杂,因为流程不是直截了当的......

4

1 回答 1

2

The usual way to do this is with a function.

def e():
    return v * 2

>>> v = 5
>>> e()
10
>>> v = 6
>>> e()
12

I must also say that I'm not in favor of functions that don't take their input as explicit parameters. Grabbing a global is cheating.

于 2019-12-10T21:31:31.807 回答