簡體   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