我的代码是:
import time
class Stopwatch (object):
def start (self):
self.beginningTime = time.time()
self.fehlerzahl = 1
def stop (self):
self.endTime = time.time()
self.time = self.endTime - self.beginningTime
def fehler(self):
self.fehlerzahl = self.fehlerzahl + 1;
def getTime (self):
return(self.time + self.fehlerzahl * 2)
当我调用fehler()(函数名是德语)函数时,python会给出以下错误跟踪:
Python 3.2.3 (default, Mar 1 2013, 11:53:50)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import stopwatch
>>> c = stopwatch.Stopwatch()
>>> c.fehler()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "stopwatch.py", line 10, in fehler
self.fehlerzahl = self.fehlerzahl + 1;
AttributeError: 'Stopwatch' object has no attribute 'fehlerzahl'
>>>
请告诉我为什么它跑不动。你知道吗
谢谢
你忘了按秒表打电话了。你知道吗
这里的问题是
fehler()
函数试图增加一个还不存在的属性。你知道吗从代码中,
start()
函数是定义fehlerzahl
属性的地方。在调用fehler()
之前,必须先调用此函数:在尝试操作变量之前,需要先定义变量。您可以先调用
start()
函数,也可以在代码的前面定义fehlerzahl
;可能是在__init__
函数中。你知道吗从OP's comment来看,似乎有人假设
start()
函数是类构造函数—事实并非如此。python类构造函数被命名为__init__
,因此基本上只需将函数名start
更改为__init__
。你知道吗相关问题 更多 >
编程相关推荐