- 论坛徽章:
- 4
|
type(name, bases, dict)
Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statements create identical type objects:
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
看手册还看不懂么...
blog = '''{
url: 'http://txw1958.cnblogs.com',
uid: 100000
}'''
agent = eval(blog, type('Dummy', (dict,), dict(__getitem__=lambda s,n:n))())
Eval函数包括两个参数:
第一个参数是语句, 被当作一条代码执行, 这个eval就是生成一个字典.
第二个参数是 type('Dummy', (dict,), dict(__getitem__=lambda s,n:n))(), 看过上边的说明你就知道这是生成了一个对象, 红色括号是调用类Dummy的构造函数生成对象. 这个对象作为eval执行环境的全局变量.
那么type函数包括3个参数, 其目的是生成基类为dict的, 并且拥有__getitem__方法的类, 名字叫做Dummy. lambda第一个参数s是self,第二个参数n就是n,直接返回n.
关键就到了, eval的第二个参数要求是个字典, 你看type()()正好生成了一个字典的派生类. 然而eval的第二个参数的意图是生成blog的执行全局变量表, 那么url和uid两个东西调用__getitem__直接返回自身, 最后就是生成了blog这个字典.
blog字典的key只能是数值或者字符串类型吧, 可是这里并没有看到lambda做n到str的转换, 那么极有可能url和uid本身就是str/int类型. |
|