繁体   English   中英

"如何正确重载 __add__ 方法?"

[英]How to properly overload the __add__ method?

我需要写一门涉及日期的课程。 我应该重载+<\/code>运算符以允许将天数添加到日期中。 解释它是如何工作的: Date<\/code>对象以(年、月、日)的格式表示为 (2016, 4, 15)。 向此添加整数 10 应该会产生 (2016, 4, 25)。 Date<\/code>类的值self.year<\/code> 、 self.month<\/code> 、 self.day<\/code> 。

我的问题是代码应该以Date + 10<\/code>和10 + Date<\/code>的形式工作。 Date - 1<\/code>也应该在添加负天数的意义上起作用。 Date(2016, 4, 25) - 1<\/code>返回Date(2016, 4, 24)<\/code> 。

我的代码以Date + 10<\/code>的形式完美运行,但不是10 + D<\/code>或D - 1<\/code>的形式。

def __add__(self,value):
    if type(self) != int and type(self) != Date or (type(value) != int and type(value) != Date):
        raise TypeError
    if type(self) == Date:
        day = self.day
        month = self.month
        year = self.year
        value = value
    if type(value) != int:
        raise TypeError
    days_to_add = value
    while days_to_add > 0:
        day+=1
        if day == Date.days_in(year,month):
            month+=1
            if month > 12:
                day = 0
                month = 1
                year+=1
            day = 0
        days_to_add -=1
    return(Date(year,month,day))

__radd__<\/code><\/a>处理右侧加法,因此您也需要实现它。

我在您的实现中看到了一些缺陷,因此我建议您使用datetime<\/code><\/a>模块(尤其是datetime.timedelta<\/strong>类)<\/em>来至少正确处理基本的日期算术:

import datetime

class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def as_date(self):
        return datetime.date(self.year, self.month, self.day)

    def __add__(self, other):
        if isinstance(other, int):
            date = self.as_date() + datetime.timedelta(days=other)
            return Date(date.year, date.month, date.day)
        else:
            raise ValueError("int value is required")

    def __radd__(self, other):
        return self.__add__(other)

    def __sub__(self, other):
        return self.__add__(-other)

    def __rsub__(self, other):
        raise RuntimeError("Doesn't make sense.")

    def __repr__(self):
        return str(self.as_date())

暂无
暂无

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

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