Skip to main content
 首页 » 编程设计

python之子类 super 返回 self 应该返回子类

2024年10月25日9lyj

我正在尝试扩展 datetime.date 类允许添加 int 而不是使用 timedelta 对象:

class Date(datetime.date): 
    def __add__(self, other): 
        if isinstance(other, int): 
            other = datetime.timedelta(days=other) 
        return super(Date, self).__add__(other) 

问题是上面的 __add__() 方法将返回 datetime.date 的实例而不是 Date。

据我所知,没有办法让 super().__add__() 知道 Date 类型。最优雅的解决方案是从 datetime.date 复制整个 __add__() 方法并添加我的额外代码。有没有办法在 Date.__add__() 方法中将 datetime.date 对象转换为 Date 对象?

这里是一个突出问题的片段:

D = Date(2000,1,1) 
d = D + 1 
type(d) # datetime.date instead of Date 

编辑:我在查看 datetime.py 后的第一个解决方案(搜索“class date”)就是这样做的:

class Date(datetime.date): 
    def __add__(self, other): 
        if isinstance(other, int): 
            other = datetime.timedelta(days=other) 
        d = super(Date, self).__add__(other) 
        self.__year = d.year 
        self.__month = d.month 
        self.__day = d.day 
        return self # this is of type datetime.date 

好吧,我想我会指出我的第一次尝试是这样的:

class Date(datetime.date): 
    def __add__(self, other): 
        if isinstance(other, int): 
            other = datetime.timedelta(days=other) 
        d = super(Date, self).__add__(other) 
        d.__class__ = Date 
        return d 

这是行不通的,因为(正如我所怀疑的那样)datetime 模块在 C 中并且根据 this post对于此类类型,您不能分配给 __class__。我有点困惑 datetime.py 中的代码是干什么用的。

请您参考如下方法:

添加后,只需从datetime.date 创建另一个Date 对象并像这样返回

    def __add__(self, other): 
        if isinstance(other, int): 
            other = datetime.timedelta(days=other) 
        result = super(Date, self).__add__(other) 
        return Date(result.year, result.month, result.day) 

这是一个测试,

D = Date(2000, 1, 1) + 1 
print(type(D), D) 
# (<class '__main__.Date'>, Date(2000, 1, 2))