Python:变量不在范围内,因为它是实例级变量。未定义全局名称
我正在学习的课程:Python:变量不在范围内,因为它是实例级变量。未定义全局名称,python,class,csv,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 在解释程序中,我尝试:
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
我们非常感谢任何指导方向
解决方案:
下面是我正在处理的代码,其中包含了解决方案。这项工作仍在进行中:
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()
filename
不是全局变量。它属于process\u csv
的一个实例。您可以使用self.filename
访问它
def printfn(self):
print self.filename
filename
在第一个示例中不是全局变量(或作用域中的变量)。它是类级别的实例级别(类的实例)变量。在printfn
中,您应该执行以下操作:
def printfn(self):
print self.filename
您的第二个示例之所以有效,是因为当您在贴花
filename
之后立即执行process\u csv(filename)
时,它就在范围内。感谢您为我尝试学习的内容提供了术语。我已经读了好几个小时了,然后才来询问堆栈溢出问题。有时这是一个艰难的世界。也许在codereview堆栈交换中这样问会更好。@jmunch:问题是答案中的术语是错误的filename
不是类级变量,而是实例级变量。@Matthias:类的实例。类级别不是意味着相同吗,还是类级别意味着静态变量?@xbonez:类级别变量在实例之间共享。
def printfn(self):
print self.filename