【发布时间】:2015-04-16 13:28:48
【问题描述】:
我有一个这样的目录结构:
home/
main.py
lib/
mylib/
Textfile_Class.py
Excelfile_Class.py
globals.py (has all the global variables declared here)
functions.py
我在main.py 中使用创建了Textfile_class 的对象
txt = TEXT(file).
现在,我想在创建Excelfile_Class 的对象期间使用此变量txt 进行一些操作(例如,如果txt 对象中的变量值为5,则在Excelfile_Class ) 中执行某些操作
在Excelfile_Class 中,我还导入了所有全局变量。字符串变量可以在那里访问,但我不知道为什么这个对象txt 在那里无法访问。无论我在Excelfile_Class(self.line_count = txt.count) 中引用txt,我都会遇到以下错误:AttributeError: 'NoneType' object has no attribute 'count'
请帮助我了解为什么会发生这种情况,即使我已经在一个单独的文件中定义了所有变量并在所有文件中导入了这些变量。
例如: main.py
path = os.path.abspath('./lib')
sys.path.insert(0, path)
from mylib.Textfile_class import *
from mylib.Excelfile_Class import *
from mylib.globals import *
from mylib.functions import *
if __name__ == "__main__":
txt = TEXT(file)
xcel = EXCEL(file)
例如 globals.py
global txt, xcel
txt=None
xcel=None
例如 Textfile_class.py
from globals import *
class TEXT:
def __init__(self, filename):
self.count = 0
with open(filename) as fp:
for line in fp:
self.count = self.count + 1`
如 Excelfile_Class.py
from globals import *
class EXCEL:
def __init__(self, filename):
self.line_count = 0
self.operation(filename)
def operation(self, file):
self.line_count = txt.count
if self.line_count:
self.some_operation()
else:
self.other_operation()
【问题讨论】:
-
你能提供一个short, self-contained, correct example吗?否则我们能做的最好的就是猜测正确的答案。我确实知道的一件事是,在
Excelfile_Class中,当您使用txt时,它是None,而不是您所期望的。这就是为什么你会收到AttributeError -
@WayneWerner 我提供了我的代码的一个小版本,现在请帮忙。
-
考虑到字符串“no_of_lines_in_file”没有出现在您发布的代码中的任何位置,很难确定该错误来自何处以及它的含义......
-
@twalberg 更正了问题。
标签: python class python-2.7 object python-import