您的位置:首页 > 编程语言 > Python开发

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