我正在尝试实现表示https://pypi.python.org/pypi/datetime-interval/0.2之后的(周期性)时间间隔的数据类型。我已经定义了一个Interval
对象,并尝试使用附加属性PeriodicInterval
从period
对象继承:
from datetime import date, timedelta, datetime
class Interval(object):
"""
An interval represents a duration of time and its location on the
timeline. It can be any of the following:
- start and end dates (or datetimes)
- a start date (or datetime) and a timedelta
- a timedelta and an end date (or datetime)
Provides the following operators:
for a date and an Interval:
in
"""
def __init__(self, start=None, duration=None, end=None):
# Type checking:
assert isinstance(start, date) or (start is None)
assert isinstance(duration, timedelta) or (duration is None)
assert isinstance(end, date) or (end is None)
# Fill in the missing value:
if (duration is not None) and (end is not None) and (start is None):
start = end - duration
elif (start is not None) and (end is not None) and (duration is None):
duration = end - start
elif (start is not None) and (duration is not None) and (end is None):
end = start + duration
# Assign the values:
self.start = start
self.duration = duration
self.end = end
def __contains__(self, time):
"""
Checks if a date is contained within the Interval, e.g.:
>>> datetime.now() in Interval(datetime.now(), timedelta(1))
True
"""
assert isinstance(time, date), "The argument 'time' should be a date."
return (self.start <= time) and (time <= self.end)
class PeriodicInterval(Interval):
def __init__(self, period=None, **kwargs):
super(PeriodicInterval, self).__init__(kwargs)
if __name__ == "__main__":
periodic_interval = PeriodicInterval()
但是,这会在类型检查中导致以下AssertionError
:
Traceback (most recent call last):
File "/home/kurt/dev/scratch/Furion_scheduler/interval.py", line 67, in <module>
periodic_interval = PeriodicInterval()
File "/home/kurt/dev/scratch/Furion_scheduler/interval.py", line 50, in __init__
super(PeriodicInterval, self).__init__(kwargs)
File "/home/kurt/dev/scratch/Furion_scheduler/interval.py", line 20, in __init__
assert isinstance(start, date) or (start is None)
AssertionError
我不明白为什么以这种方式实例化PeriodicInterval
会导致错误。如果我使用Interval
实例化interval = Interval()
,则不会出现错误。造成这种情况的原因是什么?
答案 0 :(得分:3)
在调用父构造函数时,您需要使用double star(**)运算符来展开字典关键字参数:
class PeriodicInterval(Interval):
def __init__(self, period=None, **kwargs):
super(PeriodicInterval, self).__init__(**kwargs)