inheritance
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Jun 12 12:28:00 EDT 2003
"Sean Ross" <frobozz_electric at hotmail.com> wrote in
news:bca8di$e84$1 at driftwood.ccs.carleton.ca:
> class Base:
> def __init__(self, value):
> self.value = value
> def __mul__(self, other):
> return self.__class__(self.value * other.value)
>
> class Child(Base):
> def __init__(self, value):
> Base.__init__(self, value)
>
> x = Base(2)
> y = Base(3)
> z = Child(4)
> w = Child(5)
> print x*y
> print z*w
>
> """OUTPUT
><__main__.Base instance at 0x009991E0>
><__main__.Child instance at 0x009991E0>
> """
But:
>>> x*z
<__main__.Base instance at 0x009392A0>
>>> z*x
<__main__.Child instance at 0x00934520>
For consistency you may need to base the type on both self and other.
e.g.
class Base:
def __init__(self, value):
self.value = value
def __mul__(self, other):
if issubclass(self.__class__, other.__class__):
resType = self.__class__
else:
resType = other.__class__
return resType(self.value * other.value)
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list