overriding method that returns base class object

Paul McGuire ptmcg at austin.stopthespam_rr.com
Tue Feb 17 03:29:44 CET 2004


"Aahz" <aahz at pythoncraft.com> wrote in message
news:c0rmod$gso$1 at panix3.panix.com...
<snip>
>
> class A:
>     def a(self):
>         return self.__class__()
> --
OP can't do this, can't get at source code of A.

Assuming that you don't want to write __init__() to take an A argument, you
need something like:

class B(A):
    def makeFromAnA(other):  # other is an A instance
        # construct a B - could pass initialization args from
        # other if this is part of the interface
        newB = B()

        # ... copy base class A fields from other to newB here ...

        # ... add B-ish stuff to newB here ...

        return newB
    makeFromAnA=staticmethod(makeFromAnA)

    def a(self):
        return B.makeFromAnA( A.a() )

Here's an example:
import random
class Point2D(object):  # pretend this is implemented in C, so we can't
change the code
    def __init__(self,xval,yval):
        self.x = xval
        self.y = yval
    def randomPoint():
        return Point2D( random.random()*100, random.random()*100 )
    randomPoint=staticmethod(randomPoint)

class Point3D(Point2D):  # not really good O-O design, but that's not the,
um, point
    def __init__(self,xval,yval,zval):
        self.x = xval
        self.y = yval
        self.z = zval
    def make3DPtFrom2DPt(other):
        print "Make 3D pt from",other
        return Point3D(other.x,other.y,0)
        # or if the __init__'s are not similar,
        # manually assign fields
        newPt3D = Point3D(0,0,0)
        newPt3D.x = other.x
        newPt3D.y = other.y
        return newPt3D
    make3DPtFrom2DPt=staticmethod(make3DPtFrom2DPt)
    def randomPoint():
        newPt = Point3D.make3DPtFrom2DPt( Point2D.randomPoint() )
        newPt.z = random.random()*100
        return newPt
    randomPoint=staticmethod(randomPoint)

print Point2D.randomPoint()
print Point3D.randomPoint()

-- Paul





More information about the Python-list mailing list