How do you do a python 'eval' only within an object context?

前端 未结 4 2038
慢半拍i
慢半拍i 2021-02-14 14:41

Is it possible to do something like

c = MyObj()
c.eval(\"func1(42)+func2(24)\")

in Python..i.e. have func1() and func2() be evaluated within th

4条回答
  •  我寻月下人不归
    2021-02-14 15:04

    You might have a look at the accepted answer to this question: "Getting the block of commands that are to be executed in the with-statement".

    This has been a helpful way for me to create my own contexts in which math operations on rectangular arrays, such as Python Pandas data frames, "just work" without needing to bother with the ugly extra Pandas syntax. For example, when I write "a = x*y" inside of the context, it automatically assigns a as an attribute to the context object, and it knows to perform vectorial operations with the context object's x and y attributes.

    I've found this context stuff to be very very helpful, despite the fact that whenever I ask on StackOverflow, I often get trollish responses that it must not be what I really want to do.

    You could probably get this to work for the context in which eval looks for functions too.

提交回复
热议问题