A Trivial Question
wuwei23 at gmail.com
Fri Sep 30 05:29:51 CEST 2011
On Sep 29, 8:06 am, Chris Rebert <c... at rebertia.com> wrote:
> Try this:
> def trial():
> class Foo(object):
> def __init__(self):
> print("Hello, world!")
While this will display "Hello, world!" in the way required, with a
slight adjustment you end up with something potentially a little more
myfoo = trial()
You'll see the same behaviour, but now myfoo refers to the Foo()
object that was created inside trial. This makes trial an object
factory. If you return an uninstantiated Foo instead:
MyFoo = trial()
foo = MyFoo()
Then trial is a class factory, creating and returning a class.
Factories can be handy if you're wanting to create dynamic classes
based on run time information.
def __init__(self, file):
self.file = file
if format == 'json':
print 'json processing goes here'
elif format == 'html':
print 'html processing goes here'
>>> JSONReader = reader_factory('json')
>>> j = JSONReader('file1')
json processing goes here
This is a trivial example which would probably be better handled by
subclasses, but is meant to be indicative of what's possible.
More information about the Python-list