如何正确重载__add__方法? [英] How to properly overload the __add__ method?

查看:156
本文介绍了如何正确重载__add__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个涉及日期的课程.我应该重载+运算符,以允许将几天添加到日期中.解释其工作方式:Date对象以(年,月,日)格式表示为(2016,4,15).将整数加10会得到(2016,4,25). Date类具有值self.yearself.monthself.day.

I am required to write a class involving dates. I am supposed to overload the + operator to allow days being added to dates. To explain how it works: A Date object is represented as (2016, 4, 15) in the format (year, month, date). Adding integer 10 to this should yield (2016, 4, 25). The Date class has values self.year, self.month, self.day.

我的问题是代码应该以Date + 10以及10 + Date形式工作.另外,Date - 1应该在增加负数天的意义上起作用. Date(2016, 4, 25) - 1返回Date(2016, 4, 24).

My problem is that the code is supposed to work in the form Date + 10 as well as 10 + Date. Also Date - 1 should work in the sense of adding a negative number of days. Date(2016, 4, 25) - 1 returns Date(2016, 4, 24).

我的代码以Date + 10的形式完美运行,但没有以10 + DD - 1的形式运行.

My code works perfectly in the form of Date + 10 but not in the form 10 + D or D - 1.

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

这些是我得到的错误

TypeError: unsupported operand type(s) for +: 'int' and 'Date'

TypeError: unsupported operand type(s) for -: 'Date' and 'int'

推荐答案

__radd__ 处理右侧添加,因此您也需要实现它.

__radd__ handles right side addition so you need to implement that as well.

我发现您的实现存在一些缺陷,因此建议您使用 datetime 模块(尤其是 datetime.timedelta 类)至少可以正确处理基本日期算术:

I am seeing some flaws in your implementation so I recommend you using datetime module (especially datetime.timedelta class) to at least handle basic date arithmetic correctly:

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


演示:


Demo:

>>> date = Date(2015, 10, 23)
>>> print date + 10 # __add__ is called
2015-11-02

>>> print 20 + date # __radd__ is called
2015-11-12

>>> print date - 25 # __sub__ is called
2015-09-28

>>> print 25 - date # __rsub__ is called 
RuntimeError: Doesn't make sense

这篇关于如何正确重载__add__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆