2017-03-09 98 views
2

我有这个奇怪的问题,在我的程序给我这个错误消息,当我运行代码:蟒蛇不会recognice我的功能

Traceback (most recent call last): 
    File "\\srv-fons-02\USV_Home$\6357\inf\Phyton\classes test 1.py", line 38, in <module> 
    time = Time(7, 61, 12) File "\\srv-fons-02\USV_Home$\6357\inf\Phyton\classes test 1.py", line 8, in __init__ 
    self = int_to_time(int(self)) NameError: name 'int_to_time' is not defined 

它告诉我的功能int_to_time没有定义,虽然它是。我也只是在我的__init__中得到这个问题,而不是在我使用它的其他地方(例如add_time,在__add__中使用)。我不知道它为什么在某些功能上起作用。我试图取消int_to_time()__init__并没有得到一个错误信息,即使我使用__add__艰难)。

如果任何人都可以帮助我,这将是伟大的,因为我卡在atm。

这是我的代码:

class Time: 
    def __init__(self, hour=0, minute=0, second=0): 
     self.hour = hour 
     self.minute = minute 
     self.second = second 
     if not 0 <= minute < 60 and 0<= second < 60: 
      self = int_to_time(int(self)) 

    def __str__(self): 
     return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) 

    def __int__(self): 
     minute = self.hour * 60 + self.minute 
     second = minute * 60 + self.second 
     return int(second) 

    def __add__(self, other): 
     if isinstance(other, Time): 
      return self.add_time(other) 
     else: 
      return self.increment(other) 

    def __radd__(self, other): 
     return other + int(self) 


    def add_time(self, other): 
     seconds = int(self) + int(other) 
     return int_to_time(seconds) 

    def increment(self, seconds): 
     seconds += int(self) 
     return int_to_time(seconds) 
    """Represents the time of day. 
    atributes: hour, minute, second""" 

time = Time(7, 61, 12) 

time2 = Time(80, 9, 29) 

def int_to_time(seconds): 
    time = Time() 
    minutes, time.second = divmod(seconds, 60) 
    time.hour, time.minute = divmod(minutes, 60) 
    return time 


print(time + time2) 
print(time + 9999) 
print(9999 + time) 
+2

在该类之前移动该函数或将其添加为方法。 – sascha

+3

您在定义“int_to_time()”之前创建了两个''Time''对象 - 当然''__init __()''期间它是不可用的。当你开始添加时,该功能已被定义,因此它可以工作。只需在课程结束后将该功能移动几行即可。 – jasonharper

+0

是啊,我看到了thx家伙,你也可以做一个方法,不使用它的方法?如果是的话如何? (我仍然在学Python,刚开始上课) –

回答

2

说的int_to_time该调用之前提出已经看到的定义是问题的事实。

您定义int_to_time前初始化2个Time对象:

time = Time(7, 61, 12) 

time2 = Time(80, 9, 29) 

def int_to_time(seconds): 
    time = Time() 

和内部Time.__init__您一定条件后,调用int_to_time。如果符合该条件,则拨打int_to_time将失败。

只需在之后移动初始化,定义就足够了。由于int_to_time与您的Time类似乎也是密切相关的,因此将其定义为该类的@staticmethod并不是一个好主意,并且不用担心定义何时作出。

+0

好吧,这解释了很多哈哈,我应该总是首先初始化函数,或者如果可能的话整合它们 –