473,396 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Factory function to generate a named class

I have a situation where I have, in a string, the name of a class I want an
instance of. I've written a factory function to generate the class for me:

def controllerFactory( controllerRequired, model ):
if controllerRequired == "ViewController":
return ViewController( model )
elif controllerRequired == "FontController":
return FontController( model )
elif controllerRequired == "ColourController":
return ColourController( model )
else:
raise TypeError

Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?
Jul 18 '05 #1
4 4121
Derek Fountain wrote:
Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?


class FontController:
def __init__(self, model):
pass

class Model:
pass

def getClass(classname, modulename="__main__"):
return getattr(__import__(modulename, globals(), locals(), [classname]),
classname)

model = getClass("Model")()
print getClass("FontController")(model)

Should be fairly self-explanatory :-)

Peter
Jul 18 '05 #2
Populate a dict with a mapping from class names to class objects:

d = {}
def register(cls):
d[cls.__name__] = cls

def factory(clsname, model):
try:
factory = d[clsname]
except KeyError:
raise TypeError, "Class %s not registered" % clsname

return factory(model)

class ViewController: pass
register(ViewController)

If you absolutely want this to be automatic, a metaclass trick can
probably be played to do it. Something like:
class FactoryMeta(type):
def __init__(cls, name, bases, dict):
super(FactoryMeta, cls).__init__(name, bases, dict)
register(cls)

class Factory(object):
__metaclass__ = "FactoryMeta"
del d["Factory"] # Unregister this "abstract" class

All code is untested.

Jeff

Jul 18 '05 #3
Jeff Epler wrote:
Populate a dict with a mapping from class names to class objects:


He already has such a dictionary. It's globals(). :-)

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ Golf is a good walk spoiled.
\__/ Mark Twain
Jul 18 '05 #4
Hello Derek,
Is there a way to generate an instance of a class given the class name at
runtime? If so, what, in newbie terms, is it?


If you don't mind using "eval" then:

from types import ClassType
def gen_class(name):
try:
c = eval(name)
if type(c) != ClassType:
return None
return c
except NameError:
return None

HTH.
Miki
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am...
17
by: Medi Montaseri | last post by:
Hi, Given a collection of similar but not exact entities (or products) Toyota, Ford, Buick, etc; I am contemplating using the Abstraction pattern to provide a common interface to these products....
6
by: Johan Bergman | last post by:
Hi, Maybe someone can help me with this one. The following describes a somewhat simplified version of my problem, but I think it will be sufficient. I want to use class factories (virtual...
2
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the...
10
by: Chris Croughton | last post by:
What do people call their factory functions? 'new' is not an option (yes, it can be overloaded but has to return void*). The context is: class MyClass { public: // Factory functions...
3
by: Paramesh | last post by:
Hello friends, My friend asked me this question: This question regards proprietary software (of which I am one of the developers), so I cannot post actual code for this question. I will try...
8
by: Craig Buchanan | last post by:
I've seen design patterns for class factories that work well to create (fetch) objects, but I haven't seen anything about how to persist the class' data when it has changed. Is this done thru the...
6
by: GroupReader | last post by:
In my app, I have two very similar static classes. After long thought, I've decided *yes - keep them static*. - Sometimes I will want to use Static Class A, and somtimes I will want to use...
1
by: =?Utf-8?B?RXJpYw==?= | last post by:
I am using the factory method to solve a problem where a factory can produce product. I have a base factory class and a base product class. The problem that I am having is that for every product...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.