我有一个奇怪的问题,当我运行代码时,我的程序会给我这个错误消息:
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__
中使用的add_time
)。我不知道为什么它能和一些函数一起工作。我尝试过取消__init__
中的int_to_time()
,但没有收到错误消息(即使我使用__add__
)。你知道吗
如果有人能帮我那就太好了,因为我被困在自动取款机里了。你知道吗
这是我的密码:
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)
调用
int_to_time
是在定义出现之前进行的,这是一个问题。你知道吗在定义
int_to_time
之前初始化两个Time
对象:在
Time.__init__
内部,在特定条件之后调用int_to_time
。如果满足该条件,对int_to_time
的调用将失败。你知道吗只要将初始化移到定义之后就足够了。由于
int_to_time
似乎也与您的Time
类密切相关,因此将它定义为该类的@staticmethod
并消除所有关于何时定义的担忧并不是一个坏主意。你知道吗相关问题 更多 >
编程相关推荐