无法理解的Python OOP

2024-10-02 08:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是:

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'
>>> 

请告诉我为什么它跑不动。你知道吗

谢谢


Tags: 函数inimportselfobjecttimedefline
2条回答

你忘了按秒表打电话了。你知道吗

这里的问题是fehler()函数试图增加一个还不存在的属性。你知道吗

从代码中,start()函数是定义fehlerzahl属性的地方。在调用fehler()之前,必须先调用此函数:

import stopwatch
c = stopwatch.Stopwatch()
c = stopwatch.start()
c.fehler()

在尝试操作变量之前,需要先定义变量。您可以先调用start()函数,也可以在代码的前面定义fehlerzahl;可能是在__init__函数中。你知道吗

OP's comment来看,似乎有人假设start()函数是类构造函数—事实并非如此。python类构造函数被命名为__init__,因此基本上只需将函数名start更改为__init__。你知道吗

相关问题 更多 >

    热门问题