Reputation: 211
I have this weird problem where my program will give me this error message when I run my code:
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
It tells me the function int_to_time
isn't defined, while it is. I also only get this problem in my __init__
and not in other places where I use it (add_time
that gets used in __add__
for example). I don't know why it does work with some functions. I have tried canceling the int_to_time()
in __init__
and didn't get an error message even tough I use __add__
).
If anybody could help me that would be great, cause I am stuck atm.
This is my code:
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)
Upvotes: 2
Views: 170
Reputation: 160447
The fact that the invocation of int_to_time
is made before the definition has been seen is the problem.
You initialize two Time
objects before defining int_to_time
:
time = Time(7, 61, 12)
time2 = Time(80, 9, 29)
def int_to_time(seconds):
time = Time()
and inside Time.__init__
you invoke int_to_time
after a certain condition. If that condition is met, the call to int_to_time
will fail.
Just moving the initialization after the definition suffices. Since int_to_time
also seems closely related to your Time
class it wouldn't be a bad idea to define it as a @staticmethod
for that class and drop all worries about when the definition is made.
Upvotes: 2