Python:变量不在范围内,因为它是一个实例级变量。未定义全局名称

时间:2014-03-11 05:02:39

标签: python class csv

我正在处理的课程:

import csv
from itertools import islice

class process_csv(object):

    def __init__(self, filename):
        self.filename = filename

    def printfn(self):
        #global filename ??? this is wrong?
        print filename

在解释者中我尝试:

Python 2.7.3 (default, Sep 26 2013, 20:08:41) 
[GCC 4.6.3] on linux2
>>> from csv_reader import process_csv
>>> instance1 = process_csv('some_name.csv')
>>> instance1.printfn()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "csv_reader.py", line 11, in printfn
    print filename
NameError: global name 'filename' is not defined

但是,当我从命令行运行python csv_reader.py时,脚本按预期执行:

if __name__ == '__main__':

    filename = 'MEE682.csv'
    g = process_csv(filename)
    g.printfn()

非常感谢任何指导方向。

解决方案:

以下是我正在处理包含该解决方案的代码。它仍在进行中:

import csv
from itertools import islice

class process_csv(object):

    def __init__(self, filename):
        self.filename = filename

    def printfn(self):
        """ Used for learning how to print the filename :D """
        print self.filename


    def row_count(self):
        """ Returns the csv row_count """
        number_of_rows = len(list(csv.reader(open(self.filename))))
        return number_of_rows

    def read_csv_row(self, row_number):
        """ Returns the contents in row_number """
        try:
            print "Read Row: "+str(row_number)
            with open(self.filename,'rb') as f:
                read_as_csv = csv.reader(f,delimiter='\t', quotechar='"')
                list(islice(read_as_csv,row_number))
                current_row = read_as_csv.next()
        except StopIteration:
            current_row = None
        return current_row


    def assigned_row_titles(self, row_number):
        """ Creates a dictionary with assigned row titles """

        with open(self.filename, 'r') as f:
            current_row = self.read_csv_row(row_number)
            if current_row is not None:
                # EDIT these to suit the format of the csv file
                result = { 'pallet_number' : current_row[0] ,
                           'category' : current_row[1] , 
                           'offer_id_orig' : current_row[2] , 
                           'title' : current_row[3] ,
                           'quantity' : current_row[4] , 
                           'msrp' : current_row[5] ,
                           'offer_id_scanned' : current_row[6] , 
                           'sku' : current_row[7] }
            current_row = None
        return result

    def check_csv_sku(self):
        """ Checks the number of rows that have a sku """
        row_count = self.row_count()
        tot = 0
        tot_read = 0
        tot_skipped = 0
        for row_number in xrange(1,row_count):

            result = self.assigned_row_titles(row_number)
            tot += 1
            if result['sku'] is not "":
                #print str(result)
                tot_read += 1
                ### TODO ###
                # Process the result perhaps add another method like get_item_info_from_website()
            if result['sku'] is "":
                #print 'Skipped: '+str(row_number)
                tot_skipped += 1


        print "Total lines read: "+str(tot)
        print "Total lines with sku: "+str(tot_read)
        print "Total lines skipped: "+str(tot_skipped)


if __name__ == '__main__':

    ### (note to self) examples on usage ###
    filename = 'MEE682.csv'
    # create the class instance
    g = process_csv(filename)
    # process the csv and check how many have been processed
    print g.check_csv_sku()
    # read row 14
    print g.read_csv_row(14)
    # read row 18 and assign titles to a dictionary
    print g.assigned_row_titles(18)
    # prints filname
    g.printfn()
    # print the row count
    print g.row_count()

2 个答案:

答案 0 :(得分:4)

filename不是全局变量。它属于process_csv的实例。您可以使用self.filename访问它。

def printfn(self):
    print self.filename

答案 1 :(得分:1)

在第一个示例中,

filename不是全局变量(或作用域中的变量)。它是类级实例级(类的实例)变量。在printfn中,您应该执行以下操作:

def printfn(self):
        print self.filename

您的第二个示例有效,因为当您在结束process_csv(filename)后立即执行filename时,它就在范围内。