__init__中的super()似乎没有实现父对象的默认关键字参数

时间:2016-11-22 11:51:02

标签: python

我正在尝试实现表示https://pypi.python.org/pypi/datetime-interval/0.2之后的(周期性)时间间隔的数据类型。我已经定义了一个Interval对象,并尝试使用附加属性PeriodicIntervalperiod对象继承:

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(),则不会出现错误。造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:3)

在调用父构造函数时,您需要使用double star(**)运算符来展开字典关键字参数:

class PeriodicInterval(Interval):
    def __init__(self, period=None, **kwargs):
        super(PeriodicInterval, self).__init__(**kwargs)