我刚接触编程需要一点帮助理解类

时间:2018-03-14 12:23:06

标签: python class csv

为什么这不起作用我已将此代码编写为函数,它工作正常 但是当我试图把它变成一种方法时

    import csv
    import datetime

    today = datetime.date.today()

    todayStr = str(today)

    def query(self,q):
            self.q = q
            with open('rodata.csv','r')as r:
                reader = csv.reader(r)
                for row in reader:
                    for field in row:
                        if field == q:
                            print(row)
    Logger = logger


    run = True
    while run:
        Logger.query(todayStr)
        run = False

我得到了回报 TypeError:query()缺少1个必需的位置参数:'q'

1 个答案:

答案 0 :(得分:2)

要创建课程,首先需要class className,在您的情况下logger。然后,您不会遍历行的每个列/字段,您需要将其分开。最后,您需要在类创建中添加括号。

import csv
import datetime

today = datetime.date.today()

todayStr = str(today)

# add this line
class logger:
    def query(self,q):
        self.q = q
        with open('rodata.csv','r') as r:
            reader = csv.reader(r)
            for row in reader:
                # add this line, as row currently looks like ['timestamp a b c ...']
                row=row[0].split()
                for field in row:
                    if field == q:
                        print(row)
#add parenthesis
Logger = logger()


run = True
while run:
    Logger.query(todayStr)
    run = False

要记住的其他事项是query方法当前没有返回任何内容。