2017-09-15 82 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?

相關問題