class factory

Andrew Dalke adalke at mindspring.com
Wed Aug 20 10:28:39 CEST 2003


Nick Keighley:
> I'm a Python beginner and I'm would like to write a function that
> returns a class (perhaps a tad ambitious...).

There's

class MyClass:
  pass

def fctn():
    return MyClass

or you can make the class inside of the function

def fctn():
    class MyClass:
      pass
    return MyClass

> I'd like to generate a class on-the-fly from a parameter (a dictionary).
> Can Python do this sort of stuff? Does the mean I have to mess with
> the dreaded meta-classes?

Well, *what* do you want to do?

>>> def fctn(d):
...   class MyClass:
...     def get(self, x):
...        return d[x]
...   return MyClass
...
>>> klass = fctn({"A": 1, 2: "B"})
>>> klass
<class __main__.MyClass at 0x01351810>
>>> instance = klass()
>>> instance.get("A")
1
>>>

>>> import types
>>> def fctn(name, d):
...  return types.ClassType(name, (), d)
...
>>> fctn("YoYo", {"around": "world", "walk": "dog"})
<class __main__.YoYo at 0x01351900>
>>> klass = _
>>> inst = klass()
>>> inst.walk
'dog'
>>>

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list