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

时间:2016-11-19 14:23:36

标签: python class python-3.x python-module arrow-python

我正在尝试扩展arrow并且无法理解如何复制基类的功能。这可能是由于对如何扩展模块中的类缺乏清晰的理解(我的arrow案例强调 - 这就是说问题可能更普遍而不仅限于arrow)。

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方法,该方法将返回“今天”,“明天”或“更晚”。我第一次尝试这个:

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 sourcesget位于ArrowFactory。如果我延长ArrowFactory而不是Arrow,我将能够使用get而不是now()

这就是我要处理的问题:上面的“基本用法”表明我可以调用arrow.whatever_is_available,无论它是否在类Arrow中定义,或者ArrowFactory
这是如何工作的?
如何添加when方法以保留arrow的其余部分(及其所有方法)?

1 个答案:

答案 0 :(得分:1)

  
      
  • 可扩展为您自己的箭头派生类型
  •   

是Arrow的文档中突出显示的features之一,它实际演示了exactly how to create and use a custom Arrow subclass

  

工厂

     

使用工厂将Arrow的模块API用于自定义箭头派生   类型。首先,派生你的类型:

>>> 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
     

然后获取并使用工厂:

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

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

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

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