大家好,我有一个与时间相关的类,例如你输入两次,你可以将它们相加(现在超过 23:59:59 并不重要)或将它们相乘等等。默认输入为零。还有一个返回当前时间的函数。我可以调用 time = Time()
返回 0:00:00
,time = Time(12)
返回 12:00 :00
.
我遇到的问题是,我想调用 time = Time('now')
并且它应该使用函数 now()
存储当前时间,编辑应该在 __init__()
中完成(如果您不喜欢 now()
您可以更改它)。但是,如果我将 time_now = ''
作为第一个参数,它就不起作用,当我将它作为最后一个参数时也是如此,因为当我写 time = Time('now')
它需要字符串 'now'
并希望将其转换为小时。
我知道有时间模块可以做到这一点,但这是出于学习目的。
我的代码:
import random, time
class Time:
def __init__(self, hours=0, minutes=0, seconds=0, time_now=''):
# if time_now == 'now':
# now()
time = abs(3600*hours + 60*minutes + seconds)
self.hour = time//3600
self.min = time//60%60
self.sec = time%60
def __repr__(self):
return '{}:{:02}:{:02}'.format(self.hour,self.min,self.sec)
def __add__(self, other):
if isinstance(other, Time):
return Time(self.hour+other.hour, self.min+other.min, self.sec+other.sec)
if isinstance(other, int):
return Time(self.hour, self.min, self.sec+other)
__radd__ = __add__
def __sub__(self, other):
return Time(seconds = self.__int__() - other.__int__())
def __mul__(self, other):
return Time(self.hour*other.hour, self.min*other.min, self.sec*other.sec)
def __int__(self):
return 3600*self.hour + 60*self.min + self.sec
def __eq__(self, other):
return self.__int__() == other.__int__()
def __lt__(self, other):
return self.__int__() < other.__int__()
#writing out hour/min/sec what we want
def __getitem__(self, key):
if key == 0:
return self.hour
if key == 1:
return self.min
if key == 2:
return self.sec
#time now
def now():
a=(time.localtime()[3:6])
return Time(a[0],a[1],a[2])
最佳答案
Python 没有方法 overloading ,所以你唯一的选择就是“玩弄”参数:
你可以做一些恕我直言非常糟糕的事情(在阅读了 @ ivan-pozdeev 在这个答案中的评论后,将非常糟糕降级为meeeeh...所以,所以 )
class Time:
def __init__(self, hours=0, minutes=0, seconds=0, time_now=''):
if hours == 'now':
tmp_t = now()
self.hour = tmp_t.hour
self.min = tmp_t.min
self.sec = tmp_t.sec
else:
t = abs(3600*hours + 60*minutes + seconds)
self.hour = t//3600
self.min = t//60%60
self.sec = t%60
那......好吧,这有效:
>>> a = Time('now')
>>> print vars(a)
{'sec': 20, 'hour': 15, 'min': 18}
>>>
>>> a = Time(hours=19, minutes=4, seconds=5)
>>> print vars(a)
{'sec': 5, 'hour': 19, 'min': 4}
但这使得代码处于非常奇怪的状态。非常难读。我当然会尝试完全不同的方法......
我还将 __init__
中的 time
变量更改为 t
,因为这与 time
名称冲突导入时间
关于python - 接受单个字符串而不是普通参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257991/