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

我有两个py文件。 名为test的包内有a.py和b.py(有__init__.py

我想访问下面a.py中定义的属性self.items

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]

从一个不同的py文件b.py [下],所以在b.py我导入了一个模块,即

import a

#now 

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

should'nt上面打印mag,因为我该怎么办?


(a)和(b)看到这些问题。 我认为这取决于正在使用的编译器/解释器。 在我的情况下,你的代码不会给我超过递归深度,但是这样做

希望能帮助到你。


循环进口。 a.py导入bb.py再次导入a 。 鸡/蛋问题! python无法为你解决这个问题,所以它会警告你最大递归深度(它会一直从a跳到b到a到b跳到......)。

您必须修复它,以便导入是单向的。


你有一个循环依赖: a是导入b ,然后导入a 。 由于这两种进口都是模块级别的,所以它们永远无法完成。

在你的情况下,你可以通过将import b移动到getMats方法来修复它。

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

上一篇: how to access attributes initialized in class constructor of different py file?

下一篇: Python: read and execute lines from other script (or copy them in)?