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

James_Althoff at i2.com James_Althoff at i2.com
Mon Sep 24 13:04:02 EDT 2001


Paul,

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.

Jim

==================================

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
subclasses
        return myclass.subclassDict.get(sides)

    getSubclassWithSides = classmethod(getSubclassWithSides)

    def newInstanceWithSides(myclass,sides,*pargs,**kargs):  # main factory
function
        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

Polygon.registerSubclass(Triangle,3)


class Square: pass

Polygon.registerSubclass(Square,4)


class Rotating: pass

class RotatingPolygon(Polygon,Rotating):

    ## class methods

    def getSubclassWithSides(myclass,sides):  # override superclass class
method
        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

C:\>python
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