[Tutor] Dynamically generated classes

Rasjid Wilcox rasjidw at gmail.com
Thu Dec 23 09:14:21 CET 2010


Hi all,

I've been playing with dynamically generated classes.  In particular:

class ClassMaker(object):
    def __init__(maker_self, name):
        maker_self.name = name
        #
        class Foo(object):
            def __init__(self):
                self.parent = maker_self
            def whoami(self):
                print 'I am a Foo instance made by %s' % self.parent.name
        maker_self.Foo = Foo
        #
        class Bar(object):
            def __init__(self):
                self.parent = maker_self
            def whoami(self):
                print 'I am a Bar instance made by %s' % self.parent.name
        maker_self.Bar = Bar

>>> a = ClassMaker('Alice')
>>> b = ClassMaker('Bob')
>>> af = a.Foo()
>>> ab = a.Bar()
>>> bf = b.Foo()
>>> bb = b.Bar()
>>>
>>> af.whoami()
I am a Foo instance made by Alice
>>> ab.whoami()
I am a Bar instance made by Alice
>>> bf.whoami()
I am a Foo instance made by Bob
>>> bb.whoami()
I am a Bar instance made by Bob
>>> isinstance(bb, b.Bar)
True
>>> a.Foo is b.Foo
False

The actual use case is a system where there are multiple databases of
essentially the same form, where a is database A, and b is database B,
and Foo and Bar represent tables in both the databases.  af would be
the Foo table in database A, and bf would be the Foo table in database
B.

My question is: is there a better way?  Based on my playing with the
above, it all seems to do what I want.  My only concern is that I've
not seen this idiom before, and perhaps there is a simpler or more
standard way?

Cheers,

Rasjid.


More information about the Tutor mailing list