0

I've got an error: NameError: name 'convert_symbol_to_int' is not defined when I run this code:

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()

I really cannot understand why this error happens. Why can't I access convert_symbol_to_int? How should I fix this?

cezar
  • 11,616
  • 6
  • 48
  • 84
user8563636
  • 163
  • 1
  • 5
  • 12

2 Answers2

1

you should use

man = self.convert_symbol_to_int(row[9])
Max
  • 1,283
  • 9
  • 20
0

Exactly as Kalyan Reddy already answered, you have to call the method with self, which is a pointer to the class itself. The following example shows the difference between externally declared functions and methods defined within the class:

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

The purpose of self has already been explained in this question: What is the purpose of self?

cezar
  • 11,616
  • 6
  • 48
  • 84