简体   繁体   中英

How to send a value to exec's running code

First , I have two classes like this:

class A(object):
    def foo(self, context):
        print(context)

class B(object):
    def foo(self, context):
        print(context)

Notice the context variable here.

Second , I want to call A and B in exec like this:

body = """
a = A()
a.foo()
b = B()
b.foo()
"""
exec(body)

I also have some other classes which use context .

Which means that I don't want the context variable appeared in the body code. It's been generated in other place. And I want to send it by exec or other methods.

So how can I do this?

You can make context a global variable instead:

class A(object):
    def foo(self):
        print(context)

class B(object):
    def foo(self):
        print(context)

body = """
a = A()
a.foo()
b = B()
b.foo()
"""
context = 'foobar'
exec(body)

This outputs:

foobar
foobar

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