Python, adding methods to a class, Error: global name is not defined
我试图理解为什么我的方法
1 2 3 4 5 6 7 | Traceback (most recent call last): File"/Users//Desktop/temp.py", line 33, in <module> currenttime.increment4(4000) File"/Users//Desktop/temp.py", line 22, in increment4 newtime = float(total_seconds).make_time() AttributeError: 'float' object has no attribute 'make_time' >>> |
第33行是:
1 | currenttime.increment4(4000) |
号
第22行是:
1 | newtime = float(total_seconds).make_time() |
整个过程如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Time: def printTime(self): print str(time.hours)+":"+str(time.minutes)+":"+str(time.seconds) def make_time (self): time = Time () time.hours = self / 3600 time.minutes = (self % 3600) / 60 time.seconds = (self % 3600) % 60 return time def covertTOseconds (self): hours = self.hours * 3600 minutes = self.minutes * 60 seconds = self.seconds amt_in_seconds = hours + minutes + seconds return amt_in_seconds def increment4 (self, increaseINseconds): total_seconds = self.covertTOseconds() + increaseINseconds newtime = float(total_seconds).make_time() newtime.printTime() currenttime = Time() currenttime.hours = 3 currenttime.minutes = 47 currenttime.seconds = 45 currenttime.increment4(4000) |
。
您需要稍微修改代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Time: def printTime(self, time): print str(time.hours)+":"+str(time.minutes)+":"+str(time.seconds) def increment4(self, increaseINseconds): seconds = self.covertTOseconds() + increaseINseconds time = self.makeTime (seconds) print time def makeTime(self, totalseconds): time = Time () time.hours = totalseconds / 3600 time.minutes = (totalseconds % 3600) / 60 time.seconds = (totalseconds % 3600) % 60 return time def covertTOseconds(self): hours = self.hours * 3600 minutes = self.minutes * 60 seconds = self.seconds totalseconds = hours + minutes + seconds return totalseconds |
如错误所示,
既然你已经更新了这个问题,在我看来,你可能想要做的是创建一个这样的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Time: def __init__(self): self.hours = None self.minutes = None self.seconds = None self.total_seconds = None def to_seconds(self): hours = self.hours * 3600 return (self.hours * 3600) + (self.minutes * 60) + self.seconds def increment(self, x): self.total_seconds = self.to_seconds() + x self.hours = self.total_seconds / 3600 self.minutes = (self.total_seconds % 3600) / 60 self.seconds = (self.total_seconds % 3600) % 60 self.__str__() def __str__(self): print("{0}:{1}:{2}".format(self.hours, self.minutes, self.seconds)) |
号
然后您可以按如下方式使用该类:
1 2 3 4 5 6 | c_time = Time() c_time.hours = 3 c_time.minutes = 47 c_time.seconds = 45 c_time.increment(4000) |
此输出:
1 | 4:54:25 |
。