python variables, classes

2019-05-23 14:21发布

Dear All, Trying to learn python, classes, and how to pass variables between. Going through a learning guide here, and am having trouble with the following Error:

TypeError: unbound method scan() must be called with lexicon instance as first argument (got str instance instead)

Can someone please help me understand this better? THANKS!!!

class lexicon (object):
  def __init__(self,data):
    self.direction = data
    self.words = data.split()

  def scan(self):
    return self.words

def main():
    stuff = raw_input('> ') 
    x = lexicon.scan(stuff)

if __name__ == '__main__':
 main()

标签: python class
2条回答
姐就是有狂的资本
2楼-- · 2019-05-23 14:53

You have to instantiate an object of type lexicon before you can invoke one of its methods. i.e.

lex = lexicon(data)
lex.scan()
查看更多
狗以群分
3楼-- · 2019-05-23 15:03

In addition to what Jim said, self is automatically passed in for you. (And it's not required to be called self but calling it something else will just confuse yourself and other people)

查看更多
登录 后发表回答