[英]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對象不是迭代器。
正如Andrea(+1)所指出的,你需要告訴python你想在self對象上調用next()方法,所以你需要將它self.next(currentState)
。
另請注意,您已定義了不正確的初始化程序(也稱為構造函數)。 你必須使用雙下划線:
__init__(...
代替:
_init_(...
否則它只是一種方法 - 在對象creataion時不調用。
請改用self.next(currentState),否則它指的是迭代器的next()方法,而不是你的類
錯誤意味着它所說的內容。 當你使用next(iterable)
, next
嘗試調用iterable
的next
方法 。 但是,當你做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.