我有一个奇怪的问题,当我运行代码时,我的程序会给出以下错误消息:
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 = 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
并不是一个坏主意,并且放下所有关于定义何时制定的担忧。
关于python 无法识别我的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696358/