2011-09-07 182 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。