how to access attributes initialized in class constructor of different py file?

I have two py files. a.py and b.py inside a package called test (has __init__.py )

and I want to access attribute self.items defined in the a.py below

import b

class Window(object):
    def __init__(self):
        self.items={'Magenta':'mag','Grey':'gre','Red':'red'}
    def getMats():
        newobj=b.BAR()
        selected = newobj.type_of_mats[1]

from a different py file b.py[below] so in b.py I imported the a module ie

import a

#now 

obj = a.Window()
print obj.items['Magenta']
class BAR(object):
    def myMat(self):
        type_of_mats=['ground', 'corridor', 'Outdoor']

should'nt the above prints mag since or how else I should do it ?


see these stackoverflow questions on circular imports (a) and (b). I think it depends on the compiler / interpreter being used. In my case your code does not give me recursion depth exceeded, but this does

Hope it helps.


Circular import. a.py imports b and b.py imports a again. Chicken/egg problem! And python cannot solve that for you, so it warns you about a maximum recursion depth (it keeps on jumping from a to b to a to b to a...).

You'll have to fix it so that the import is one-way only.


You have a circular dependency: a is importing b , which is in turn importing a . Since those two imports are at module level, they can never complete.

In your case, you could fix it by moving the import b into the getMats method.

链接地址: http://www.djcxy.com/p/54800.html

上一篇: 写入模块

下一篇: 如何访问在不同py文件的类构造函数中初始化的属性?