2011-04-08 57 views
2

亲爱的所有人,试图学习python,类,以及如何传递变量。在这里阅读学习指南,并且遇到以下错误:python变量,类

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

有人能帮助我更好地理解这一点吗? 谢谢!

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

回答

7

你必须实例lexicon类型的对象,然后才能调用其方法之一。即

lex = lexicon(data) 
lex.scan() 
+0

很好的阅读理解绑定与未绑定方法。 http://docs.python.org/reference/datamodel.html和http://docs.python.org/library/stdtypes.html#methods – 2011-04-08 21:50:47

+0

谢谢你们!将'instantiate'这个词解释为'define'是否合适? 换句话说...... 您必须先定义该类中的类和函数,然后才能使用它们... – Cmag 2011-04-08 22:09:50

+0

@Clustermagnet否。因为一个类不需要'实例化'来运行它的方法,如果它们是静态或类方法。 Instaniated将被最好地描述为在内存中创建对象。静态方法和类方法作为类的一部分存在,但不需要设置类来使用它们。 – 2011-04-08 22:57:11

1

除了吉姆说的之外,self会自动传给你。 (并不需要称为self,但称之为别的东西只会让自己和其他人感到困惑)