2017-03-09 62 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

好吧,這解釋了很多哈哈,我應該總是首先初始化函數,或者如果可能的話整合它們 –