0

How to make a class which could operate like this without importing other modules?

>>date(2014,2,2) + delta(month=3)
>>(2014, 5, 2)
>>
>>date(2014, 2, 2) + delta(day=3)
>>(2014, 2, 5)
>>date(2014, 2, 2) + delta(year=1, month=2)
>>(2015, 4, 2)

This is my code:

# class delta(date):
#     year = date(year)
#     def __init__(self,y,m,d):
#         self.y = y + year
#         self.m = m
#         self.d = d
#     def __call__(self):
#         return self.y, self.m, self.d
class date(object):
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    def __call__(self):
        return self.year, self.month, self.day
3
  • 1
    does delta have to be its own class, could you just make a delta function in date class? Commented Sep 7, 2016 at 15:32
  • I made delta as Class Commented Sep 7, 2016 at 15:37
  • Sure, there are plenty of ways to do this. Check out __add__ and __iadd__. Commented Sep 7, 2016 at 15:40

1 Answer 1

1

Override the __add__ method. In the delta class give the __init__ default parameters so you can call it with only one or two arguments.

class delta():
    def __init__(self,year=0,month=0,day=0):
        self.y = year
        self.m = month
        self.d = day
    def __call__(self):
        return self.y, self.m, self.d

class date():
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day   
    def __call__(self):
        return self.year, self.month, self.day
    def isLeapYear (self):
        if ((self.year % 4 == 0) and (self.year % 100 != 0)) or (self.year % 400 == 0):
            return True
        return False
    def __add__(self,delta):
        self.year=self.year+delta.y
        self.month=self.month+delta.m
        if self.month>12:
            self.month=self.month%12
            self.year+=1
        self.day=self.day+delta.d
        if self.isLeapYear() and self.day>29:
            self.day=self.day%29
            self.month+=1
        elif not self.isLeapYear() and self.day>28:
            self.day=self.day%28
            self.month+=1
        return self.year, self.month, self.day

print(date(2014, 2, 2) + delta(year=1, month=2)) # (2015, 4, 2)

birthdate=date(1990,1,1)
currentyear=birthdate+delta(year=20,month=2,day=5)
print(currentyear) # (2010, 3, 6)
Sign up to request clarification or add additional context in comments.

1 Comment

Waow.. this is perfect Answer... Thank You Sir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.