|
Hello all, I was just messing around with a suggestion w chun (wescpy at gmail dot com) gave (to make a class that handles time, ie: import myTimec = myTime.myTime(10,30)print c 10:30d = myTime.myTime(8,45)print c + d 19:15 etc), and I was trying to make it like the str class in that, by default, when you str() a string, it returns the same object. I tried to do this with the following (irrelevant code removed), but it didn't work, despite original indications to the contrary, and I'm not sure I understand why: >>> class stime: def __init__(self, minutes, seconds=None): if seconds is None: if minutes.__class__ is stime: print minutes, type(minutes), minutes.__class__, id(minutes) self = minutes print self, type(self), self.__class__, id(self) def __repr__(self): return str(self) def __str__(self): return "%02d:%02d" % (self.minutes, self.seconds) >>> a = stime(10,3) >>> b = stime(a) 10:03 <type 'instance'> __main__.stime 12858832 10:03 <type 'instance'> __main__.stime 12858832 >>> # so, it appears to work, because it prints the same id both times. however, # . . . >>> id(a) 12858832 >>> id(b) 12858792 >>> # they're not the same anymore! and that's not all: >>> a 10:03 >>> b Traceback (most recent call last): File "<pyshell#163>", line 1, in -toplevel- b File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 20, in __repr__ return str(self) File "C:/Documents and Settings/Cookie/Desktop/stime.py", line 22, in __str__ return "%02d:%02d" % (self.minutes, self.seconds) AttributeError: stime instance has no attribute 'minutes' So, not only do the two variables not refer to the same object after exiting __init__, but b is now a broken stime instance. Anyone know what's going on? Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. |
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
