Python中的metaclass

虽然参考了几篇文章,但是没有自己亲自操刀,一直没有深入理解。

不过,自己写的怎么能用得上,现在还没有理解直接操作__dict__好呢还是使用metaclass好呢?还是二者压根不是一码事呢?

class BaseBuilderFromDict(object):
    def __init__(self,_dict_):
        self.__dict__["private"]={}
        for k, v in _dict_.items():
            self.__dict__["private"][k] = v
    def dict(self):
        return copy.copy(self.__dict__["private"])

class BasePoster(BaseBuilderFromDict):
    def __init__(self, _dict_,listShouldBeDecoded=copy.copy([])):
        BaseBuilderFromDict.__init__(self,_dict_)
        self.__dict__["_list_"]=listShouldBeDecoded
        self.__dict__["Path"]=""
        self.__dict__["PostResult"]=None
    def __getattr__(self, item):
        return self.__dict__["private"].get(item, None)
    def __setattr__(self, key, value):
        if key in self.__dict__["_list_"]:
            try:
                rlt=base64.decodestring(value)
                if value and not rlt:#用来对付中文
                    raise
            except :
                self.__dict__["private"][key]=base64.encodestring(value)
        elif key in self.__dict__["private"]:
            self.__dict__["private"][key]=value
        else:
            self.__dict__[key]=value
    def param(self):
        return "param="+urllib.quote(json.dumps(self.__dict__["private"]).replace('"',"'").replace(" ",""))#.urlencode(self.__dict__)
    def _post(self):
        try:
            json_rlt=json.loads(urllib2.urlopen(urllib2.Request(Common.Url.FULL_HOST + self.Path, self.param(), Common.Setting.HEADER)).read())
            if json_rlt["result"]=="success":
                self.PostResult={'data':json_rlt["data"]}#防止即使成功但返回null字符串的情况(null会被json加载成None)
                return self.onSuccess()
            else:
                return self.onFail()
        except:
            return self.onExcept()
    def onSuccess(self):
        return self.PostResult
    def onFail(self):
        return None
    def onExcept(self):
        return None
    def post(self):
        return self._post()
    def result(self):
        return self.post()
class BaseClass(BaseBuilderFromDict):
    def __init__(self,_dict_,sub_dict=copy.copy({})):
        BaseBuilderFromDict.__init__(self,_dict_)
        for k,v in sub_dict.items():
            self.__setattr__(k,v)
    def __setattr__(self, key, value):
        if key in self.__dict__["private"]:
            if (isinstance(value,str) or isinstance(value,unicode)) and value:
                try:
                    value=value.encode("utf-8")
                except:
                    pass
                if re.match(r"\d{4}(-\d{2}){2}\s\d{2}(:\d{2}){2}",value):#假设时间字符串没问题
                    self.__dict__["private"][key]=datetime.datetime.strptime(value,"%Y-%m-%d %H:%M:%S")
                else:
                    try:
                        self.__dict__["private"][key]=base64.decodestring(value)#测试是否为base64加密,是则解密
                    except :
                        self.__dict__["private"][key]=value
            else :
                self.__dict__["private"][key]=value
        else:
            self.__dict__[key]=value
    def __getattr__(self, key):
        if key in self.__dict__["private"]:
            return self.__dict__["private"][key]
        elif key in self.__dict__.keys():
            return self.__dict__[key]
        else:
            return None
    def getSqlInsert(self):
        sql="INSERT INTO {{table}}({columns}) VALUES({values})"
        columns=[]
        values=[]
        for k in sorted(self.__dict__["private"]):
            columns.append(k)
            values.append(self.__dict__["private"][k])
        return sql.format(columns=",".join(columns),values=",".join([str(x).join(["'","'"]) if isinstance(x,str) or isinstance(x,datetime.datetime) else str(x) for x in values]))


*********************

中文翻译:

http://blog.jobbole.com/21351/

*********************

stackoverflow原文:

http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

********************

你可能感兴趣的:(Python中的metaclass)