Python 如何从其他类中的类获取行文件?
我的问题很简单。让我用一个示例代码来解释我的问题。我开发了一个特定的文件解析器,每一行代表一个对象Python 如何从其他类中的类获取行文件?,python,class,parsing,Python,Class,Parsing,我的问题很简单。让我用一个示例代码来解释我的问题。我开发了一个特定的文件解析器,每一行代表一个对象 file = open("file.txt", "r") class Reader(object): def __init__(self): self.i = 1 // first line def readFile(self): for line in file: test2() // do
file = open("file.txt", "r")
class Reader(object):
def __init__(self):
self.i = 1 // first line
def readFile(self):
for line in file:
test2()
// do things..
class Line():
def printLine(self):
f.readline() // Need to read the current line from the readFile() loop
test()
因此,我想知道的是,如何在不重新打开文件的情况下从
test2().printLine()
中的readFile()
访问当前行?函数接受参数并返回值。使用这些功能。发送线路:
def readFile():
for line in file:
test2(line) # <-- send line to test2
// do things...
def readFile():
对于文件中的行:
test2(line)#这段代码既不是真正的Pythonic代码,也不是OO代码。在阅读了原始问题后,我认为您需要的应该是:
file_name = "file.txt"
class Reader(object):
def __init__(self, name):
self.name = name # store file name as a data member
def readFile(self):
with open(self.name, "r") as file: # with ensure proper close of file
# using data member name
for line in file: # iterate on lines
Line(line).printline() # pass the line to another object
# or: test2(line) # or to a function
# do other things...
class Line: # an auxilliary class
def __init__(self, line):
self.line = line
def printLine(self):
# use self.line here
def test2(line): # a module level function
# use line here
Reader(file_name).readFile() # create a new Reader object and calls its readfile method
为什么不直接添加line
作为printLine()
的参数?提示:您可能知道,在您的情况下,立即加载文件内容可能比让每个对象在本地打开/读取/关闭它更好(line=file.readlines()
)。在实际需要之前,我不建议考虑此类优化。无论如何,它们可能是真的,也可能不是真的。在幕后可能会运行多个级别的优化。设计干净的代码更重要。为什么定义类(Reader
,Line
)而只调用不相关的函数c(test
,test2
)。如果没有更多的澄清,这至少是事实unclear@PatrickMichel最近的编辑似乎让你的源代码变得不易理解。这不起作用,我没有收到行()中的行class@PatrickMichel因为有一半的代码丢失了(在您的问题和这里)test2
没有定义,但我想它最终会调用类Line
的printLine
方法。修复这个问题,我也会在答案中添加缺少的部分。re:pythonic:read_file():)