我有这个奇怪的问题,在我的程序给我这个错误消息,当我运行代码:蟒蛇不会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,刚开始上课) –