看到几个字典生成式,记录下来吧!

callmap={'GET':'read','POST':'create','PUT':'update','DELETE':'delete'}#def__new__(metaclass,name,bases,namespace):classTest(object):defread(self):print('get')return'get'defcreate(self):print('post')return'post'defupdate(self):print('put')return'put'cls=Test#遍历callmap字典,寻找cls类中method方法,如果有则返回键和值;如果没有,忽略crud={(http_method,None):getattr(cls,method)forhttp_method,methodinlist(callmap.items())ifgetattr(cls,method,None)isnotNone}print(crud)

结果:

{'GET':<functionTest.readat0x010C0858>,'PUT':<functionTest.updateat0x010C08E8>,'POST':<functionTest.createat0x010C08A0>}