Is there a way to instantiate a subclass from a class constructor?

James_Althoff at James_Althoff at
Mon Sep 24 19:04:02 CEST 2001


I'm not sure if I understand everything you are looking for.  But here is
an example of how to do instance creation using the new class methods in
Python 2.2 (using a Smalltalk-ish OO idiom).  The basic idea is to use
class methods for your factory functions.  The *big* advantage to using
class methods (for factory functions) instead of using module functions is
that you can define "subclass" factory functions and take advantage of
inheritance and method override.

Hope this helps.



class Polygon:

    subclassDict = {}

    ## class methods

    def registerSubclass(myclass,classObj,sides):
        myclass.subclassDict[sides] = classObj

    registerSubclass = classmethod(registerSubclass)

    def getSubclassWithSides(myclass,sides):  # we will override this in
        return myclass.subclassDict.get(sides)

    getSubclassWithSides = classmethod(getSubclassWithSides)

    def newInstanceWithSides(myclass,sides,*pargs,**kargs):  # main factory
        instance = None
        classObj = myclass.getSubclassWithSides(sides)
        if classObj:
            instance = classObj(*pargs,**kargs)
        return instance

    newInstanceWithSides = classmethod(newInstanceWithSides)

    ## add instance methods here if needed

class Triangle: pass


class Square: pass


class Rotating: pass

class RotatingPolygon(Polygon,Rotating):

    ## class methods

    def getSubclassWithSides(myclass,sides):  # override superclass class
        classObj = Polygon.getSubclassWithSides(sides)
        if classObj:
            class mixinClass(classObj,Rotating): pass
            mixinClass.__name__ = classObj.__name__ + Rotating.__name__  #
so that print will verify
            classObj = mixinClass
        return classObj

    getSubclassWithSides = classmethod(getSubclassWithSides)

    ## add instance methods here if needed

triangle = Polygon.newInstanceWithSides(3)
print triangle

square = Polygon.newInstanceWithSides(4)
print square

rotatingTriangle = RotatingPolygon.newInstanceWithSides(3)
print rotatingTriangle

rotatingSquare = RotatingPolygon.newInstanceWithSides(4)
print rotatingSquare

Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import example1
<example1.Triangle instance at 007FA8CC>
<example1.Square instance at 007FA77C>
<example1.TriangleRotating instance at 007FA67C>
<example1.SquareRotating instance at 007FA1CC>

More information about the Python-list mailing list