繁体   English   中英

exec python2 vs python3

[英]exec python2 vs python3

我正在将一个testframework从python2转移到python3。 我在执行函数更改时遇到了exec语句的麻烦。 在运行时,我决​​定根据xls文件调用哪个函数。 我试图给local()和global()并尝试execHelper而不是exec(参见下面的例子)我也尝试了exechelper函数的命名空间技术直接在testfunction中,但总是在命名空间中找不到某些名称。 .. 有什么建议么?

def execHelper(command,callerobject):
    ns = {}
    exec(command,ns)
    for name, value in ns.items():
        setattr(callerobject, name, value)

def myfunction2(val1,val2):
    return val1 * val2

class myclass():
    def myfunction1(self,val1,val2):
        return val1 + val2

    def test(self):
        a = 5
        self.b = 10
        exec("result = self.myfunction1(a,self.b)+myfunction2(a,self.b)")
        print(result)


test = myclass()
test.test()
def myfunction2(val1,val2):
    return val1 * val2

class myclass():
    def myfunction1(self,val1,val2):
        return val1 + val2


    def test(self):
        a = 5
        self.b = 10
        exec("global result;result = self.myfunction1(a,self.b)+myfunction2(a,self.b)")
        print(result)


test = myclass()
test.test()

在exec函数中使用global

Python 2中的exec和Python 3中的exec()之间存在很大差异。因此在python 3中,我们必须将结果varialbe带入exec()的范围。

暂无
暂无

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

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