我有這個奇怪的問題,在我的程序給我這個錯誤消息,當我運行代碼:蟒蛇不會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)
在該類之前移動該函數或將其添加爲方法。 – sascha
您在定義「int_to_time()」之前創建了兩個''Time''對象 - 當然''__init __()''期間它是不可用的。當你開始添加時,該功能已被定義,因此它可以工作。只需在課程結束後將該功能移動幾行即可。 – jasonharper
是啊,我看到了thx傢伙,你也可以做一個方法,不使用它的方法?如果是的話如何? (我仍然在學Python,剛開始上課) –