Friday, 15 August 2014

Using object of imported class as global variable of another class in Python -


I have participated in the following problem in Python. I suppose you have 3 files:

1 ) A.py (defines class A):

  class A: def a_method (self): print "global usage experiment" / code>  

2) B.py (defines class B which uses class A's global object method):

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

3) global_ex.py:

  import from obj_a Obj_b = B () obj_b.b_method ()   

When I run global_ex.py, I get an error:

  Error named: global name 'obj_a' is not defined   

If instead of importing another b.py, I copy them into global_ex.py I work.

What's the problem here? Generally, what is the best way to use an object's methods in an object?

Thanks in advance.

Edit:

Try:

  Import from a class B (): def __init __ (self): self.a_obj = A () DEF B_Maneth (self): Print "Calling A_the (B) B ..." self.a_obj.a_method ()   

or:

  square b (): def __init__ (self, a_inst): self.a_inst = a_inst def b_method (self): print "calling_a_dethod ) From B ... "self.a_inst.a_method ()    

No comments:

Post a Comment