0

I have a module (myMod.py) with an Object baseObj with a few methods

class baseObj(object):
    ....
    def doThing(self):
        ......

I need to create many subclasss, normal way to do this would be:

class Foo(baseObl):
    pass

class Bar(baseObl):
    pass

etc.

But there there are a lot of these.

I have the names of these subclasss in a list

subNames  = ['Foo','Bar','Lorem',...]

I can create the subclass dynamically like so (identical to the above)

Foo = type('Foo', (baseObj), {})

What I want to do is something like:

for name in subNames:
    name = type(name, (baseObj), {}) 

To create a bunch of subclasss with the names in the list.

Obviously, this dose not work.

What I found on line was doing something like this :

registry =[]
for name in subNames:
    registry[name] = type(name, (baseObj), {}) 

Which will not give me the kind if API I am looking for.

What I want to allow at the end is:

from myMod import Foo, Bar

a = Foo()
a.doThing()

b = Bar()
b.doThing()

etc.

Is there a pretty way to do this?

  • 1
    See the duplicate; one of the options there is to use the `globals()` dictionary. `globals[name] = type(name, (baseObj,), {})`. – Martijn Pieters Jul 23 '15 at 16:43
  • This still feels wrong somehow. Maybe you have a good use-case. If you want advice on a (possibly) better design, you can open a new question where you explain what you are trying to achieve. – André Laszlo Jul 23 '15 at 16:49
  • I am wrapping a JSON RPC API. The API publishes a dynamic list of objects to be manged which is the source of the name of the subs in my list. All the objects allow basic CRUD actions. Kind like WSDL for JSON. I'll crate a separate questions for that. – HmmThatsOdd Jul 23 '15 at 17:04

0 Answers0