python动态创建类
2017-02-08 19:44
246 查看
场景
python是一门动态语言,开发者可以再运行时,创建新的类型。其场景: 依据远端服务器功能而创建一个新类,调用服务器支持什么类和方法。举个列子: ('/cat/meow', '/cat/eat', '/cat/sleep', '/dog/bark', '/dog/eat', '/dog/sleep') 创建具有特定方法的动态类来调用服务器相应的远端方法。
type()
这个需求,就意味着不能用 已知道的语法。
class A(object): ... class B(A): ...
我们可以用exec,绕道解决这个问题。
exec('class %s(object): pass' % 'Cat') 但是,这不是正确的方式。生成的代码,容易损坏、错误。
用 type() 是个更好的方法,简单、执行快:不需要解析字符串。
1 # -*- coding: utf-8 -*- 2 #!/usr/bin/python 3 4 5 def remote_call(arg1): 6 print arg1 7 8 new_class = type('Cat', (object,), {'meow': remote_call('meow'), 'eat': remote_call('eat'), 'sleep': remote_call('sleep')}) 9 10 #Another example 11 #item = type('TYPE_KEYLIST_V1', (object,), { "name": "", "cname": "key_command", "type": "T_KEYLIST_V1" }) 12 13 type(object) 14 type(new_class) 15 print new_class.__name__ 16 print new_class.__bases__ 17 18 ###AttributeError: type object 'Cat' has no attribute 'value' 19 #print new_class.value 20 21 #Add the property of instance only 22 new_class.value = 11 23 print new_class.value ~ ~
Result
在开发中,不得不参照外部,如:数据库schema或者网页服务,而创建一个类时,这个方式非常有用。
Reference :
http://henry.precheur.org/python/Dynamically%20create%20a%20type%20with%20Python.html
相关文章推荐
- 使用Python创建MySQL数据库实现字段动态添加以及动态的插入数据
- python 动态创建类
- python 动态创建类 type
- python 动态创建一个类
- python 动态创建字典名
- Python 动态创建函数【转】
- python动态创建对象变量
- python中利用exec动态创建函数
- python动态创建类的声明
- python动态创建变量
- Python创建动态二维数组
- Python 字典的创建赋值和动态扩展
- Python中动态创建类实例
- python实现在sqlite动态创建表的方法
- python 动态创建类
- python 动态创建类
- Python实用程序案例——动态创建类
- Python中动态创建类实例的方法
- python动态创建变量
- python学习笔记2-强大的动态创建