A Trivial Question

alex23 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!")
>     Foo()
> trial()

While this will display "Hello, world!" in the way required, with a
slight adjustment you end up with something potentially a little more
useful:

def trial():
    class Foo(object):
        def __init__(self):
            print("Hello, world!")
    return Foo()

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:

def trial():
    class Foo(object):
        def __init__(self):
            print("Hello, world!")
    return Foo

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 reader_factory(format='json'):
  class Reader(object):
    def __init__(self, file):
      self.file = file
    if format == 'json':
      def process(self):
        print 'json processing goes here'
    elif format == 'html':
      def process(self):
        print 'html processing goes here'
  return Reader

>>> JSONReader = reader_factory('json')
>>> j = JSONReader('file1')
>>> j.process()
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 mailing list