推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
agentwx
V2EX  ›  Python

python 动态生成 class 的问题

  •  
  •   agentwx · Nov 21, 2015 · 4288 views
    This topic created in 4000 days ago, the information mentioned may be changed or developed.

    昨天晚上看到一个 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

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

    谢谢

    12 replies  •  2015-11-23 11:30:01 +08:00
    pupboss
    pupboss
    Nov 21, 2015
    1
    可以看看 python 的元编程,之前有过接触,不过我也没搞明白
    ethego
    ethego
    Nov 21, 2015
    2
    在廖雪峰的 python 教程里搜索"metaclass"
    justfly
    justfly
    Nov 21, 2015
    3
    使用 type
    DEMONHUNTER
    DEMONHUNTER
    Nov 21, 2015
    4
    当然可以, python 的 mataclass 就是专门干这个的。
    lxy42
    lxy42
    Nov 21, 2015
    5
    type +1
    baichi
    baichi
    Nov 21, 2015
    6
    echo1937
    echo1937
    Nov 21, 2015
    7
    我大概看过 50 页元编程,发现这玩意十足黑科技。
    ericls
    ericls
    Nov 22, 2015
    8
    meta programming in python

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

    http://leeeric.com/post/a-python-web-crawler-helper/
    agentwx
    agentwx
    OP
    Nov 22, 2015
    9
    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
    agentwx
    OP
    Nov 22, 2015
    10
    @ericls 多谢,我研究下
    neoblackcap
    neoblackcap
    Nov 23, 2015
    11
    metaclass ,我不了解。我只是了解 type 函数用法而已,请去看看 type 函数的文档,自然可以解决你的问题
    agentwx
    agentwx
    OP
    Nov 23, 2015
    12
    @neoblackcap 好的 多谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2853 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 13:17 · PVG 21:17 · LAX 05:17 · JFK 08:17
    ♥ Do have faith in what you're doing.