Subclass factories?

Tim CHURCHES TCHUR at doh.health.nsw.gov.au
Sun Mar 11 19:23:24 EST 2001


Is it Pythonic to use a factory function to create subclasses? The context is a system designed to be used by non-programmers. What I would like to do is to create a subclass factory function which accepts various parameters (sorry, arguments) from the end-user, does various sanity checks on these arguments, and then creates a new class which inherits from a predefined superclass and uses the arguments to overide various attributes and/or methods from the superclass, and finally to create an instance of the new class (and return that instance). In other words, allow end users to create subclasses without having to understand the class statement (remember, they are non-programmers). 

Or perhaps I should rephrase the question: "Is it possible to use a factory function to create instances of a class in which that instance's methods (as well as its attributes) are specialised? Such specialisation would normally be done by subclassing. Can that be wrapped in a function?"

If the subclass factory approach is reasonable, what is the best way to do it? So far I been assembling the necessary statements for the new class definition into a string then exec'ing that string, but that seems rather inelegant. I'm sure there must be a better way.

The overall design goal is to provide end-users with a set of functions which they can issue at the Python prompt (or in scripts) to get most things done (i.e. "most things" within the proscribed problem domain), without preventing them from using more general Python syntax (such as the class statement) if/when they progress to that.

BTW,  regarding the "Einstein's Riddle" thread (and not wanting in any way to promote off-topic traffic...), surely no-one owns the fish because Schrodinger's cat ate it?

Tim C






More information about the Python-list mailing list