2011-09-07 72 views
3

我最近开始用Python进行编码,并遇到了将函数返回的值赋给变量的问题。将函数返回的值赋给Python中的变量

class Combolock: 
    def _init_(self,num1,num2,num3): 
     self.x = [num1,num2,num3] 
    def next(self, state): 
     print "Enter combination" 
     combo = raw_input(">") 
     if combo == self.x[state]: 
      print "Correct" 
      return 1 
     else: 
      print "Wrong" 
      return 0 
    def lock(self): 
     currentState = 0 
     while currentState < 2: 
      temp = next(currentState) 
      if temp == 1: 
       currentState = currentState + 1 
      else: 
       currentState = 99 
       print "ALARM" 

当我打电话锁定功能,我得到一个错误在该行

temp = next(currentState) 

说,一个int对象不是一个迭代器。

回答

8

您应该使用self.next(currentState),因为您需要类范围中的next方法。

功能next是全球性的,next(obj)只有在objiterator时才有效。
你可能想看看python文档中的yield statement

+1

明白了,非常感谢! – Hunterhod

0

使用self.next(currentState)代替,否则它指的是迭代器的next()方法,而不是你的类

0

的错误意味着正是它说。当您使用next(iterable)时,next会尝试调用iterablenext方法。但是,当你做dir(0)

['__abs__', 
# ... snip ... 
'__xor__', 
'bit_length', 
'conjugate', 
'denominator', 
'imag', 
'numerator', 
'real'] 

正如你所看到的,是一个整数,没有next方法。

如果您正试图调用自己的next方法,那么您需要使用self.next而不是nextnext是一个内置函数调用一个迭代的方法next让你做这样的事情:

for something in my_iterator: 
    print something 

尝试:

temp = self.next(currentState) 
4

正如安德烈(+1)指出了这一点,你需要告诉python你想调用next()方法上的自我对象,所以你需要叫它self.next(currentState)

此外,请注意,您已经定义了不正确的初始化程序(又名。构造函数)。你必须使用双下划线:

__init__(... 

代替:

_init_(... 

否则它只是一个方法 - 不叫,而对象creataion。