这里`in dic`的用法是什么
what's the usage of `in dic` here
我正在阅读 Python source codes,我在 Python-2.7.10/Lib/multiprocessing/managers.py.
中找到这段代码
我只是想知道这里的% (meth, meth) in dic
有什么用,因为我觉得%
会先关联字符串,而exec
总是returnsNone
def MakeProxyType(name, exposed, _cache={}):
'''
Return an proxy type whose methods are given by `exposed`
'''
exposed = tuple(exposed)
try:
return _cache[(name, exposed)]
except KeyError:
pass
dic = {}
for meth in exposed:
exec '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth) in dic
ProxyType = type(name, (BaseProxy,), dic)
ProxyType._exposed_ = exposed
_cache[(name, exposed)] = ProxyType
return ProxyType
您可以改写为
code = '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth)
exec code in dic
又使用 exec ... in ...
形式:
In all cases, if the optional parts [in ...
] are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are given as globals and locals, the code will be executed as if it were embedded in a class definition.
即代码将在待创建代理类型的class变量字典中执行。
我正在阅读 Python source codes,我在 Python-2.7.10/Lib/multiprocessing/managers.py.
中找到这段代码我只是想知道这里的% (meth, meth) in dic
有什么用,因为我觉得%
会先关联字符串,而exec
总是returnsNone
def MakeProxyType(name, exposed, _cache={}):
'''
Return an proxy type whose methods are given by `exposed`
'''
exposed = tuple(exposed)
try:
return _cache[(name, exposed)]
except KeyError:
pass
dic = {}
for meth in exposed:
exec '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth) in dic
ProxyType = type(name, (BaseProxy,), dic)
ProxyType._exposed_ = exposed
_cache[(name, exposed)] = ProxyType
return ProxyType
您可以改写为
code = '''def %s(self, *args, **kwds):
return self._callmethod(%r, args, kwds)''' % (meth, meth)
exec code in dic
又使用 exec ... in ...
形式:
In all cases, if the optional parts [
in ...
] are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are given as globals and locals, the code will be executed as if it were embedded in a class definition.
即代码将在待创建代理类型的class变量字典中执行。