使用cls .__ dict__生成lambda

时间:2015-06-04 16:47:30

标签: python class lambda class-method

我编写了这些类来定义HTTP响应:

from django.http import HttpResponse
import json

class BaseResponse:
    code = {
        'SUCCESS': [0, ''],
        'FAIL':[-1, '']
    }

    def __init__(self):
        pass

    @classmethod
    def response(cls, error, code, ret):
        ret = {
            'error':error,
            'code':code,
            'ret':ret
        }
        return HttpResponse(json.dumps(ret))

    @classmethod
    def responseWithCodeName(cls, codeName, ret):
        print "%s\t%s" % (codeName, ret)
        # return cls.response(cls.code[codeName][1], cls.code[codeName][0], ret)

    @classmethod
    def addCoding(cls, codename, code, msg):
        cls.code[codename]=[code, msg]

    @classmethod
    def inherCode(cls):
        cls.code.update(BaseResponse.code)

    @classmethod
    def generateResponseProperties(cls):
        for item in cls.code.keys():
            print item
            print cls.code[item]
            cls.__dict__[item] = staticmethod(
                lambda ret : cls.responseWithCodeName(item, ret)
            )


class BannerResponse(BaseResponse):
    code = dict()

class AuthResponse(BaseResponse):
    code = dict()

if __name__ =="__main__":
    BannerResponse.inherCode()
    BannerResponse.addCoding('NOBANNER', '1', "no banner got")
    BannerResponse.generateResponseProperties()
    BannerResponse.NOBANNER('nobanner')
    BannerResponse.SUCCESS('success')
    BannerResponse.FAIL('fail')

运行此代码的结果是:

FAIL
[-1, '']
NOBANNER
['1', 'no banner got']
SUCCESS
[0, '']
SUCCESS nobanner // This should be 'NOBANNER nobanner'
SUCCESS success 
SUCCESS fail // This should be "FAIL fail"

请注意generateResponseProperties()的输出是正确的!当我以这种方式使用类时,有没有python的秘密?

很抱歉,local-variables-in-python-nested-functions中的答案对我没有帮助。我已经尝试过这个问题的解决方案,但我仍然无法弄明白。

0 个答案:

没有答案