1

I have run into the following issue in Python. Suppose you have 3 files:

1) a.py (defines class A):

class A:
  def a_method(self):
    print "global var experiment"

2) b.py (defines class B that uses method of the global object of class A):

class B:
  def b_method(self):
    print "calling a_method() from B..."
      obj_a.a_method()

3) global_ex.py:

from a import A

obj_a=A()       
obj_a.a_method()

from b import B

obj_b = B()
obj_b.b_method()

When I run global_ex.py I get the error:

NameError: global name 'obj_a' is not defined

If instead of importing a.py and b.py I copy-paste them into the global_ex.py it works fine.

What is the issue here? Generally, What is the best way to use methods of one object in another object?

Thank you in advance.

1
  • well, obj_a is not defined in the global scope of b.py - would you like the interpreter to copy-paste the text of the imported module instead of using compiled bytecode? Commented Mar 28, 2013 at 0:14

1 Answer 1

1

EDITED:

Try:

from a import A

class B():

  def __init__(self):
      self.a_obj = A()

  def b_method(self):
      print "calling a_method() from B..."
      self.a_obj.a_method()

Or:

class B():

  def __init__(self, a_inst):
      self.a_inst = a_inst

  def b_method(self):
      print "calling a_method() from B..."
      self.a_inst.a_method()
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, however, I gave a simple example here. In my real case class A contains other members and methods which should be accessible by other classes. Right now I am thinking that maybe the best way would be to pass obj_A as and argument to b_method. It should work that way, shouldn't it?
@GregoryR - yes, it would work the way you mentioned and it one of the use-cases
@GregoryR: Instead of passing obj_a to b_method() every time you call it, you could also add an __init__() method to class B and pass obj_a to it just once when you construct obj_b -- of course __init__() would have to save the value for access later in b_method as needed something like what is shown in the second example of this answer.
@martineau: Thanks. When I pass obj_a to __init__() of class B, is it passed by reference? (In other words, if obj_a gets updated, will class B be aware of these updates?)
@GregoryR: Yes, since it's an instance of a mutable class.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.