1

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?

MohitC
  • 4,541
  • 2
  • 34
  • 55
wsf1990
  • 195
  • 2
  • 12

1 Answers1

1

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
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks,Your answer maybe right,and I'll test it soon.But I have many places will use this `context` variable,Not just in A,So dose it have some other methods ? – wsf1990 Oct 18 '19 at 04:16
  • I don't add context in foo method's param, Because I think can the context be defined in other place? – wsf1990 Oct 18 '19 at 04:32
  • I had test this, Which can't work, Told me that context is not defined, Because A and B not at the same place as exec. – wsf1990 Oct 18 '19 at 04:33
  • Does your test code not look like this working demo? https://repl.it/@blhsing/ExcitableMessyNewsaggregator – blhsing Oct 18 '19 at 04:34
  • More like this:https://repl.it/@shoufengwei/TechnicalBigApplicationsoftware – wsf1990 Oct 18 '19 at 04:38
  • So the classes are defined in a different module. In that case you have to import the classes from that module and assign your external value to `context` as an attribute of the module object: https://repl.it/@blhsing/TechnicalBigApplicationsoftware – blhsing Oct 18 '19 at 04:42
  • @blhsing why `object` in `class A(object)` ? . Any study link... – PIG Oct 18 '19 at 04:44
  • 1
    @PIG `object` is the base class for all new-style classes. You can read about new vs. old-style classes here: https://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python – blhsing Oct 18 '19 at 04:46
  • if i am not using `object` inside class still it is giving same result. – PIG Oct 18 '19 at 04:49
  • @PIG For the purpose of this question it makes no difference. New-style classes have several features that are not available to old-style classes. [This answer](https://stackoverflow.com/a/19950198/6890912) summarizes them well. – blhsing Oct 18 '19 at 04:53