簡體   English   中英

將函數返回的值分配給Python中的變量

[英]Assigning the value returned by a function to a variable in 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對象不是迭代器。

你應該使用self.next(currentState) ,因為你想要類范圍中的next方法。

函數next是global, next(obj)只有在obj迭代器時才有效。
您可能希望查看python文檔中的yield語句

正如Andrea(+1)所指出的,你需要告訴python你想在self對象上調用next()方法,所以你需要將它self.next(currentState)

另請注意,您已定義了不正確的初始化程序(也稱為構造函數)。 你必須使用雙下划線:

__init__(...

代替:

_init_(...

否則它只是一種方法 - 在對象creataion時不調用。

請改用self.next(currentState),否則它指的是迭代器的next()方法,而不是你的類

錯誤意味着它所說的內容。 當你使用next(iterable)next嘗試調用iterablenext 方法 但是,當你做dir(0)

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

如您所見,整數上沒有next方法。

如果您嘗試調用自己的next方法,則需要使用self.next而不是next next是一個內置函數,它調用迭代器的next方法讓你做這樣的事情:

 for something in my_iterator:
     print something

嘗試:

temp = self.next(currentState)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM