Problem of understanding inheritance
Robert Kern
robert.kern at gmail.com
Wed Dec 6 19:21:38 EST 2006
matilda matilda wrote:
> Hi all,
>
> I searched for a while, but didn't found answer to my question.
>
> I wrote the following little program:
> ====================================
> #!/usr/bin/python
> import datetime as dt
> class MyClass(dt.date):
> def __init__(self, *args, **kwargs):
> super(MyClass, self).__init__(*args, **kwargs)
>
> def addday(self, day=0):
> my = self + dt.timedelta(day)
> return my
>
> def getfirstofmonth(self):
> return self.replace(day=1)
>
>
> if __name__ == '__main__':
> my = MyClass(2006,10,1)
> print "Type before", type(my)
> my = my.getfirstofmonth()
> print "Type after", type(my)
> my = my.addday(2)
> print "Type after add", type(my)
> ====================================
>
> What I don't understand is, why the type of the returning object
> 'my' changes by executing my.addday(2).
> Why does addday return the datetime.date-object and not
> an object of class MyClass?
> What am I missing?
You did not override __add__(). I'm almost certain that the implementation of
datetime.date.__add__ creates a new datetime.date object explicitly rather than
using self.__class__ to figure out what it should construct.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list