如何延长箭头? (和模块中的类似 类)

How to extend arrow? (and similar classes in modules)

我正在尝试扩展 arrow,但无法理解如何复制基础 class 的功能。这可能是由于对如何在模块中扩展 classes 缺乏清晰的理解(我的 arrow 案例强调了这一点——也就是说这个问题可能比 [=14] 更普遍=] 仅)。

arrow基本用法:

>>> import arrow
>>> arrow.now()
<Arrow [2016-11-19T15:13:23.897484+01:00]>
>>> arrow.get("2016-11-20")
<Arrow [2016-11-20T00:00:00+00:00]>

我想添加一个 when 方法,它将 return 'today'、'tomorrow' 或 'later'。我第一次尝试这个:

import arrow

class MyArrow(arrow.Arrow):
    def __init__(self, *args):
        arrow.Arrow.__init__(self, *args)

    def when(self):
        now = arrow.now()
        end_today = now.ceil('day')
        end_tomorrow = now.replace(days=+1).ceil('day')
        start_tomorrow = now.replace(days=+1).floor('day')
        if self < end_today:
            return 'today'
        elif self < end_tomorrow:
            return 'tomorrow'
        else:
            return 'later'

if __name__ == "__main__":
    tom = MyArrow.now().replace(days=+1)
    print(tom.when())
    someday = MyArrow.get("2016-11-19")

结果是

tomorrow
Traceback (most recent call last):
  File "D:/Dropbox/dev/domotique/testing/myarrow.py", line 23, in <module>
    someday = MyArrow.get("2016-11-19")
AttributeError: type object 'MyArrow' has no attribute 'get'

所以第一部分成功了,但是 get() 失败了。我查看了 the sourcesgetArrowFactory 中。如果我扩展 ArrowFactory 而不是 Arrow 我将能够使用 get 但不能再使用 now()

这是我迷茫的地方:上面的"basic usage"表明我可以调用arrow.whatever_is_available不管它是否定义在class ArrowArrowFactory.
这是如何工作的?
如何添加我的 when 方法以保持 arrow 的其余部分(及其所有方法)不变?

  • Extensible for your own Arrow-derived types

是高亮显示之一 features in Arrow's documentation, which actually demonstrates exactly how to create and use a custom Arrow subclass:

Factories

Use factories to harness Arrow’s module API for a custom Arrow-derived type. First, derive your type:

>>> class CustomArrow(arrow.Arrow):
...
...     def days_till_xmas(self):
...
...         xmas = arrow.Arrow(self.year, 12, 25)
...
...         if self > xmas:
...             xmas = xmas.replace(years=1)
...
...         return (xmas - self).days

Then get and use a factory for it:

>>> factory = arrow.Factory(CustomArrow)
>>> custom = factory.utcnow()
>>> custom
>>> <CustomArrow [2013-05-27T23:35:35.533160+00:00]>

>>> custom.days_till_xmas()
>>> 211

然后您可以调用 factory 上的 .get.now.utcnow 方法,并使用其 .when 方法获取您的自定义子类。

这是特定于处理 Arrow 及其模块级别的 API;使用更简单的模块,您可以直接将它们的 类 子类化。