简体   繁体   中英

How to instantiate class in python dynamically?

I'm using method dispatcher in CherryPy. In the server/start.py part of the server, I need to instantiate the API classes.

To make it more modular, and not to put everything in the start.py file, I coded it like this.

So, I've a dict which has all the instantiated api classes.

services = {}
user = UserResource() #api class
foo = FooResource() #api class
services = {"user":user, "foo":foo}

class Server(object):
    """Initialise the Cherrypy app"""
    #for service in services:
    user = services.values()[0]


cherrypy.quickstart(Server())

That works. But, if I do services.keys()[0] = services.values()[0] it doesn't work at all. No routes.

How do I do such a thing? Where I don't have to assign it to a particular class inside the server class, but rather use the keys to add routes.

services.keys() simply returns a list. Setting the first element of that list to anything will have no effect.

I expect you want to do services[services.keys()[0]] = services.values()[0] , although I can't imagine what you are trying to do with that code.

Edit

OK, I think I understand what you want to do. It seems that CherryPy relies on class-level attributes to define the routes it will serve. The docs show how to do this dynamically. In your case, you could do something like this:

class Server(object):
    pass

for k, v in services:
    setattr(Server, k, v)

Note that the setattr has to be done outside the class definition itself, as the Server name doesn't exist inside the class body.

如果要具有更大的路由灵活性,请使用RoutesDispatcher

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM