tags:

views:

157

answers:

2

FILE: b.py

class B:
    def __init__(self):
        print "B"

import a

a = A()

FILE: a.py

class A(B):             ###=> B  is not  defined
    def __init__(self):
        print "A"

When I try to execute b.py, it's said that B is not defined. Am I misunderstanding "import"?

Thanks a lot if you can pointer out the problem.

+4  A: 

Because python initializes class A in its own file. It is not like a C or PHP include where every imported module is essentially pasted into the original file.

You should put class B in the same file as class A to fix this problem. Or you can put class B in c.py and import it with "from c import B".

Unknown
ore use the class's full import name: a = a.A()
reto
+4  A: 

The closest working thing to your code would be:

==== FILE: b.py ====

class B:
def __init__(self):
    print "B"

import a

if __name__ == "__main__":
    a = a.A()

==== FILE: a.py ====
import b

class A(b.B):             ###=> B  is not  defined
    def __init__(self):
        print "A"

Notice the differences:

  • Files (modules) are namespaces, if you import "a" you refer to its class A as "a.A".

  • You need to import b in a.py if you want to use it.

You want to avoid having two modules that need to include each other, by either putting everything in the same module, or splitting things up in more modules. Also, it's better to have all your imports at the head of the file, which makes this kind of monkeying impossible.

Emile