2017-09-15 69 views
0

我有一个错误:当我运行这段代码NameError: name 'convert_symbol_to_int' is not definedNameError:名字“convert_symbol_to_int的”没有定义

class ReadData(): 
    def __init__(self, sheet_path): 
     self.book = xlrd.open_workbook(sheet_path) 
     self.sheet = self.book.sheet_by_index(1) 
     self.users = [] 

    def read(self): 
     for row_index in range(2, self.sheet.nrows): 
      rows = self.sheet.row_values(row_index) 
      if rows[1] != '' and rows[2] != '' and rows[4] != '': 
       woman = convert_symbol_to_int(row[8]) 
       man = convert_symbol_to_int(row[9]) 

    def convert_symbol_to_int(self,arg): 
     if arg == '○': 
      return 2 
     elif arg == '×': 
      return 1 
     elif arg == '△': 
      return 0 
     else: 
      return -1 

x = ReadData('./data/excel1.xlsx') 
x.read() 

我真的不明白,为什么这个错误发生。 为什么我不能访问convert_symbol_to_int?我应该如何解决这个问题?

回答

1

你应该使用

man = self.convert_symbol_to_int(row[9]) 
0

准确的讲,格利扬雷迪已经回答了,你必须调用与self的方法,这是一个指向类本身。下面的示例示出了在类中定义的外部声明函数和方法的区别是:

def hello(): 
    print("hello, world!") 


class Greeting(object): 
    def __init__(self, world): 
     self.world = world 

    def hello(self): 
     print("hello, {}!".format(self.world)) 

    def make_greeting(self): 
     hello() # this will call the function we created outside the class 
     self.hello() # this will call the method defined in the class 

self目的已经在这个问题解释: What is the purpose of self?

相关问题