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()
asked Apr 8, 2011 at 21:43
Cmag
15.9k26 gold badges97 silver badges147 bronze badges
2 Answers 2
You have to instantiate an object of type lexicon before you can invoke one of its methods. i.e.
lex = lexicon(data)
lex.scan()
answered Apr 8, 2011 at 21:46
Jim Garrison
87k20 gold badges162 silver badges197 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Mike Ramirez
good reading to understand bound vs unbound methods. docs.python.org/reference/datamodel.html and docs.python.org/library/stdtypes.html#methods
Cmag
Thanks guys! Would it be appropriate to explain the word 'instantiate' as 'define'? In other words... You must define the class and functions within that class before you can use them...
Mike Ramirez
@Clustermagnet No. Because a class does not need to be 'instaniated' to run it's methods, if they are static or class methods. Instaniated would be best described as creating the object in memory. static methods and class methods exist as part of the class but the class does not need to be instinated to use them.
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)
answered Apr 8, 2011 at 21:51
David Ly
31.7k27 gold badges123 silver badges174 bronze badges
Comments
lang-py