How to combine two class? so the output can be equal...
here's my code..

class year:
    def __add__(self, year):
        return (year)   
class day: 
    def __add__(self, day):
        return (day)
class month:
    def __add__(self, month):
        return (month)
class Date:
    def __call__(self, year, month, day):
        return (year, month, day)
class Delta(year, month, day):
    def __call__(self, year, month):
        return (year, month)

date = Date()
delta = Delta()

print delta(year=5, month=6) + date(2019,5,2)

this code will make output...
>>> (5, 6, 2019, 5, 2)

Wrong output..
because, the output must be equal, like this...
>>> (2024, 11, 2)

Note: This is my homework, not allowed using import...
python2.7
thanks before :)

Recommended Answers

All 3 Replies

class Date(object):

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

    def __add__(self, other):
        if not isinstance(other,Delta):
            raise Exception("can only add Delta object")
        #FIXME handle the calendar 
        year=self.year+other.year
        month=self.month+other.month
        return Date(year,month,self.day)

    def __str__(self):
        return "("+",".join(map(str,(self.year,self.month,self.day)))+")"

class Delta(object):

    def __init__(self, year, month):
        if not (1<=month<=12) or year<0 or \
        not isinstance(year,int) or not isinstance(month, int):
            raise Exception("invalid Delta parameters")
        self.year=year
        self.month=month

    def __add__(self, other):
        return other+self

print Delta(year=5, month=6) + Date(2019,5,2)

wow thanks dude, its working :)

class delta, can't call object day ...
because class date have a object day, so object day from class delta must working too..
thanks you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.