[英]How to instantiate class in python dynamically?
I'm using method dispatcher in CherryPy. 我在CherryPy中使用方法调度程序。 In the server/start.py part of the server, I need to instantiate the API classes.
在服务器的server / start.py部分中,我需要实例化API类。
To make it more modular, and not to put everything in the start.py file, I coded it like this. 为了使其更具模块化,而不是将所有内容都放入start.py文件中,我将其编码如下。
So, I've a dict which has all the instantiated api classes. 因此,我有一个字典,其中包含所有实例化的api类。
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. 但是,如果我做
services.keys()[0] = services.values()[0]
则根本无法使用。 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. services.keys()
只是返回一个列表。 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. 我希望您想做
services[services.keys()[0]] = services.values()[0]
,尽管我无法想象您要使用该代码做什么。
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.
看来CherryPy依靠类级别的属性来定义它将服务的路由。 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. 请注意,必须在类定义本身之外完成setattr,因为服务器名称在类主体内部不存在。
如果要具有更大的路由灵活性,请使用RoutesDispatcher 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.