How to import class from class included by that class

夙愿已清 提交于 2019-12-24 13:41:22

问题


I got a weird problem that I wasn't been able to find answer all over the internet (or I don't know how to ask).

I have module AAA.py

from BBB import BBB
class AAA():
    def test(self):
        print 'AAAA'
        a = BBB()

and module BBB.py

class BBB():
    def __init__(self):
        print 'BBB'

then when I call

a = AAA()
a.test()

everything works as expected and I see output

AAAA
BBB

BUT when I try to import and use class AAA from module BBB.py

from AAA import AAA
class BBB():
    def __init__(self):
        print 'BBB'

I get following error

ImportError: cannot import name AAA

Any suggestions? I cant create circular dependencies in Python? I am using version Python 2.7.6 on Ubuntu


回答1:


Indeed - if AAA.py imports something from BBB.py at top level and vice versa, it doesn't work as intended.

There are two ways you can solve it:

  1. Import the modules from each other. This way they are both present as their namespace and will be filled during the import process.

    So just do import BBB and use BBB.BBB() for instantiating the class:

    import BBB
    class AAA():
        def test(self):
            print 'AAAA'
            a = BBB.BBB()
    
  2. Do the import where you need it:

    class AAA():
        def test(self):
            from BBB import BBB
            print 'AAAA'
            a = BBB()
    

    This way the link between the two modules is "looser" and not so tight.




回答2:


When you want to use a module in another one, you have to import it and so use import your_module. You have to type your_module.foo() if you want to use a method inside it. With the instruction from your_module import attr1, foo1, [...] you are modifying the module's global variables, so that you can use attr1 or the method foo1 as if they were in your module. A concrete example is: if you want to use the math module, you type import math and when you want to use the constant pi you type math.pi, but if you are sure there will be no clash with the other names, you'll type from math import pi and you will use the constant pi as if you declared it in your module.



来源:https://stackoverflow.com/questions/31429641/how-to-import-class-from-class-included-by-that-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!