python 动态生成 class 的问题

2015-11-21 18:33:20 +08:00
 agentwx

昨天晚上看到一个 python 包 tornadows , 可以方便的用来创建 webservice
如下
from tornadows import soaphandler
from tornadows import xmltypes
from tornadows.soaphandler import webservice

class MatchService(soaphandler.SoapHandler):
@webservice(_params=[float,float],_returns=float)
def add(self, a, b):
result = a+b
return result

看了写这些类的形式差不多多少,但是又必须要写代码
那么可不可以动态的生成这个类来被使用呢? 比如我给出一个配置信息,包括了类名,方法,方法的参数数量及类型,甚至是返回值
如何根据这个配置信息把这个类动态创建出来呢?
需要了解什么知识点?

谢谢

3049 次点击
所在节点    Python
12 条回复
pupboss
2015-11-21 18:50:44 +08:00
可以看看 python 的元编程,之前有过接触,不过我也没搞明白
ethego
2015-11-21 19:04:59 +08:00
在廖雪峰的 python 教程里搜索"metaclass"
justfly
2015-11-21 19:48:03 +08:00
使用 type
DEMONHUNTER
2015-11-21 20:33:12 +08:00
当然可以, python 的 mataclass 就是专门干这个的。
lxy42
2015-11-21 20:37:55 +08:00
type +1
baichi
2015-11-21 21:31:34 +08:00
echo1937
2015-11-21 21:42:17 +08:00
我大概看过 50 页元编程,发现这玩意十足黑科技。
ericls
2015-11-22 09:22:56 +08:00
meta programming in python

我用这个实现过一个小东西

http://leeeric.com/post/a-python-web-crawler-helper/
agentwx
2015-11-22 22:51:41 +08:00
metaclass 怎么玩呢?感觉没有这个东西,好像也是可以动态的嘛。比如
In [1]: def func_a(cls, a, b):
...: return a+b
...:

In [2]: class A(object):
...: pass
...:

In [3]: A.proper1 = "a"

In [4]: A.funca = func_a

In [5]: t = A()

In [6]: t.funca(1,2)
Out[6]: 3


正确的玩法,那么 metaclass 的正确的玩法是怎么样的呢?
agentwx
2015-11-22 22:54:04 +08:00
@ericls 多谢,我研究下
neoblackcap
2015-11-23 10:47:25 +08:00
metaclass ,我不了解。我只是了解 type 函数用法而已,请去看看 type 函数的文档,自然可以解决你的问题
agentwx
2015-11-23 11:30:01 +08:00
@neoblackcap 好的 多谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/237905

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX