简体   繁体   English

子类化一个复杂对象,并从其父类初始化一个实例

[英]Subclass a complicated object, and init an instance from its parents class

In the following example Foo class (trying to make a datetime class that has extra methods).在下面的示例Foo类中(尝试创建一个具有额外方法的datetime类)。 I also would like to be able to chain method calls (eg foo.bar().baz() ), as well as be able to pass the object to existing function which expects a datetime object.我还希望能够链接方法调用(例如foo.bar().baz() ),以及能够将对象传递给需要datetime对象的现有函数。

When instantiating it I get a TypeError as shown below:实例化它时,我得到一个TypeError ,如下所示:

from pytz import UTC
from datetime import datetime

class Foo(datetime):
    def bar(self, timezone):
        print(self.astimezone(timezone))            
        return self

now = datetime.now(UTC)
Foo(now) # TypeError: an integer is required (got type datetime.datetime)

I am guessing the error is coming from trying to make a datetime object from a datetime object.我猜的错误是由试图使即将到来datetime从一个对象datetime对象。 My question is very similar to this post Creating an object from a base class object in Python .我的问题与这篇文章Creating an object from a base class object in Python非常相似。 ie How does one initiate a child class from a parent object.即如何从父对象启动子类。 I tried the delegation solution in the post but it resulted in recursion and some messy code.我在帖子中尝试了委托解决方案,但它导致递归和一些混乱的代码。 I am thinking there must be a better way!我想一定有更好的方法!

You're inheriting the entire behaviour of the datetime class.您正在继承datetime类的整个行为。 The constructor behaves the same way as the datetime constructor, meaning it expects integers for year, month, day and so on.构造函数的行为方式与datetime构造函数相同,这意味着它需要年、月、日等整数。 datetime(datetime.now()) would fail the same way for the same reason. datetime(datetime.now())会因为同样的原因以同样的方式失败。

You can simply use Foo.now() to construct a Foo instance using the datetime.now() mechanics.您可以简单地使用Foo.now()使用datetime.now()机制构造一个Foo实例。

If you want to "augment" an existing datetime object to a Foo object, you should probably add a class method for that:如果您想将现有的datetime对象“扩充”为Foo对象,您可能应该为此添加一个类方法:

class Foo(datetime):
    @classmethod
    def from_datetime(cls, dt):
        return cls.fromtimestamp(dt.timestamp(), dt.tzinfo)

Converting the existing datetime object to a timestamp and using the fromtimestamp constructor here is probably the simplest way to copy over all the needed information.将现有的datetime对象转换为时间戳并在此处使用fromtimestamp构造函数可能是复制所有所需信息的最简单方法。 Use like:像这样使用:

foo = Foo.from_datetime(now)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM