我在python 2.7中编写了这段代码来查找Fibonnaci系列.但是我的代码中有错误:
File "Fib.py", line 2, in <module>
class Fib:
File "Fib.py", line 21, in Fib
for n in Fib(4):
NameError: name 'Fib' is not defined
Run Code Online (Sandbox Code Playgroud)
谁能解决这个bug?
class Fib:
def __init__(self,max):
self.max = max
def __iter__(self):
self.a=0
self.b = 1
return self
def __next__(self) :
fib = self.a
if fib > self.max :
raise StopIteration
a,b=b,self.a+self.b
return fib
for n in Fib(4):
print n
Run Code Online (Sandbox Code Playgroud)
免责声明:我无法从您发布的代码中重现您的错误(请参阅下面的猜测工作).但是,我仍然会收到错误,所以我会修复它们.
我明白了:
Traceback (most recent call last):
File "a.py", line 17, in <module>
for n in Fib(4):
TypeError: instance has no next() method
Run Code Online (Sandbox Code Playgroud)
看来,如果你的目标python 2.7,你已经与python 3混淆了.该__next__方法是在python 3中引入的(在PEP 3114中,如果你感兴趣的话).在python 2中,使用next.此外,由于self必须用来访问实例成员变量,a,b=b,self.a+self.b应该是self.a, self.b = self.b, self.a + self.b.这使你的代码:
class Fib:
def __init__(self, max):
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def next(self):
fib = self.a
if fib > self.max :
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
for n in Fib(4):
print n
Run Code Online (Sandbox Code Playgroud)
产生输出:
0
1
1
2
3
Run Code Online (Sandbox Code Playgroud)
请注意,更改next到__next__和改变print n,以print(n)使这项工作在Python 3(但后来不蟒蛇2.如果你想同时你需要转发next到__next__和使用括号print).
根据您的错误判断,您的原始代码可能如下所示:
class Fib:
def __init__(self,max):
self.max = max
def __iter__(self):
self.a=0
self.b = 1
return self
def __next__(self) :
fib = self.a
if fib > self.max :
raise StopIteration
a,b=b,self.a+self.b
return fib
for n in Fib(4): # Note that this makes the loop part of the class body
print n
Run Code Online (Sandbox Code Playgroud)
缩进for循环使它成为类主体的一部分,并且因为类名是一个尚不可访问的名称,所以它会引发一个NameError.有关更简单的示例,请尝试(它会产生类似的错误):
class A:
print A
Run Code Online (Sandbox Code Playgroud)
因此,您遇到的错误很可能只是缩进混淆.但是,使用迭代器的好主意.
| 归档时间: |
|
| 查看次数: |
269 次 |
| 最近记录: |