pythoncsv.reader文件方法在其参数中使用的对象内调用时失败

2024-10-02 10:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用csv.reader文件(),但如果reader()的参数是该对象本身(即“self”),则当我从类中的方法使用它时,它将失败。失败是非直觉的。当我打电话的时候csv.reader文件()从物体外部看,一切正常。有人能解释一下我犯了什么概念错误吗?希望我的解释有点道理:读/调用代码可能更容易。你知道吗

您可以看到,在main中,我首先直接调用readDirList()方法,一切都很顺利。但是,如果我调用dirList类的readDirList()方法(应该做同样的事情),我会得到奇怪的“no next()method”错误。我糊涂了。你知道吗

谢谢你看!你知道吗

(在LinuxMint17.3中使用Python2.7.6)顺便说一句,如果在main中省略“mdl”部分,直接跳到“mdl2”部分,我也会得到相同的区域。 #!/usr/bin/python文件 #例子:为什么csv.reader.next文件()不起作用

import csv

class dirList(object):
    def __init__(self):
        self.inFile = None
        return
    # a dirList object is iterable so that csv.reader can be used
    def __iter__(self):
        return self
    def next(self):
        line = self.inFile.next()
        return line
    def readDirList(self, sourceFile):
        # read csv file
        self.infile = open(sourceFile)
        print type(self) #yup, self is indeed of the right class which DOES have next() method
        rdr = csv.reader(self)
        for csvline in rdr:
            print csvline
        self.infile.close()
        return True
#----------------------------------------------------------------------
if __name__ == "__main__":
    # this works as expected
    mdl = dirList()
    mdl.inFile = open('tin.csv', 'r')
    rdr = csv.reader(mdl)
    for aaa in rdr:
        print aaa
    mdl.inFile.close()
    # when doing the same thing within a method of the object, it fails with:
    # AttributeError: 'NoneType' object has no attribute 'next'
    mdl2 = dirList()
    mdl2.readDirList('tin.csv')
    sys.exit()
#---- contents of file 'tin.csv' is as follows
"""
a,b,c
d,e,f
1,3,4
"""

Tags: 文件csv方法selfreturnobjectmaindef

热门问题