简体   繁体   English

python将dict对象视为_csv.reader

[英]python regard a dict object as a _csv.reader

i write a python program to convert a csv file to a list of my own class,here is the code 我编写了一个python程序将csv文件转换为我自己的类的列表,这是代码

class node:
    def __init__(self):
        self.cst_code = 0
        self.detail={};
    def setdata(self,CST_CODE,DATE,NUMBER):
        self.cst_code = CST_CODE
        self.detail[DATE]=NUMBER
    def add(self,DATE,NUMBER):
        if detail.get(DATE):
            self.detail[DATE]+=NUMBER
        else:
            self.detail[DATE]=NUMBER
    def sort(self):
        sorted(self.detail.items(),key = lambda e:e[0],reverse=True)
    def get_code(self):
        return self.cst_code

detail is a dict object,but python regard it as a _csv.reader detail是一个dict对象,但是python将其视为_csv.reader

    ---> 16         if detail.get(DATE):
         17             self.detail[DATE]+=NUMBER
         18         else:

AttributeError: '_csv.reader' object has no attribute 'get'

did anyone meet the same question and get a solution? 有谁遇到相同的问题并获得解决方案?

You've probably created a variable named detail in an outer scope to that of method node.add() . 您可能已经在方法node.add()的外部作用域中创建了一个名为detail的变量。 Because you are referring to detail , and there is no object named detail in the method's scope, the outer scope will be checked for an object with that name. 因为您是指detail ,并且方法的作用域中没有名为detail对象,所以将在外部作用域中检查具有该名称的对象。 You might have an instance of a csv.reader defined outside of the method. 您可能在方法外部定义了一个csv.reader实例。

It would seem that your method should actually be referring to self.detail , not detail . 看来您的方法实际上应该指的是self.detail而不是detail To access the dictionary stored in the instance, not an outer scope: 要访问存储在实例中的字典,而不是外部作用域:

def add(self,DATE,NUMBER):
    if self.detail.get(DATE):        # N.B. use self
        self.detail[DATE]+=NUMBER
    else:
        self.detail[DATE]=NUMBER

Note also that method node.sort() is missing a return . 还要注意,方法node.sort()缺少return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM