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

2024-04-20 14:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图扩展^{},但无法理解如何复制基类的功能。这可能是由于对如何在模块中扩展类缺乏清晰的理解(我的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方法,它将返回'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()。你知道吗

这就是我困惑的地方:上面的“基本用法”表明我可以调用arrow.whatever_is_available,不管它是在类Arrow还是ArrowFactory中定义的。
这是怎么回事?
如何添加when方法以保持arrow的其余部分(及其所有方法)不变?你知道吗


Tags: 方法selfgettodayreturndaysnowreplace
1条回答
网友
1楼 · 发布于 2024-04-20 14:29:47
  • Extensible for your own Arrow-derived types

是Arrow文档中突出显示的features之一,它实际演示了exactly how to create and use a custom ^{} 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的;对于更简单的模块,您可以直接对它们的类进行子类化。你知道吗

相关问题 更多 >