简体   繁体   中英

Problem using exec within class' function in Python

The following code works as expected

name = "Test"
myname = ""
exec('myname ="' + name + '"')
print(myname)

Which shows as result:

Test

Problem

However, if I define the same within a function in a class and execute it I get as result an empty string.

class new(object):
    def __init__(self, name):
        self.print(name)

    def print(self, name):
        myname = ""
        exec('myname ="' + name + '"')
        print(myname)

a = new("My name")

The above is a toy example code of a bigger code.

Question

How to define the function so as to get the same result? The exec function is actually needed in the bigger code.

You can pass a dictionary as the globals (or locals) for exec .

def print(self, name):
    d = {"myname": ""}
    exec('myname ="' + name + '"', d)
    print(d["myname"])

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