zoukankan      html  css  js  c++  java
  • python中的操作符重载示例

    最近在做一个权限系统,期望的效果如下:
    权限部分是一个二级结构, contenttype.action
    假定对外暴露的接口为 perms 变量,期望能通过 if perms.contentname 来判断用户是否拥有contentname中的任一action的权限,通过 if perms.contentname.actionname来判断用户是否具有contentname下的actionname权限。
    为了方便用户使用,决定使用python的操作符重载。
    具体代码如下:

    class PermLookupDict(object):
    def __init__(self, datas, content_name):
    self.datas = datas
    self.content_name = content_name.strip()
    def __repr__(self):
    return "datas = %s, and content_name = %s" %(str(self.datas), self.content_name)

    def __getitem__(self, perm_name):
    return self.__getattr__(perm_name)

    def __getattr__(self, perm_name ):
    result = False
    try:
    perms = self.datas[self.content_name]
    if perm_name.strip() in perms:
    result = True
    else:
    result = False
    except:
    result = False

    return result

    def __nonzero__(self):
    if self.datas.has_key( self.content_name ):
    return True
    else:
    return False



    class PermWrapper(object):
    def __init__(self, datas):
    self.datas = datas
    def __getitem__(self, content_name ):
    return self.__getattr__(content_name)
    def __getattr__(self, content_name ):
    return PermLookupDict(self.datas, content_name)
    def __iter__(self):
    # I am large, I contain multitudes.
    raise TypeError("PermWrapper is not iterable.")
    def __getstate__(self):
    return self.__dict__
    def __setstate__(self, d):
    self.__dict__.update(d)

    其中最主要的两个操作符重载就是 PermLookupDict中的__nonzero____getattr__, if perms.contentname的最终调用函数就是__nonzero__



  • 相关阅读:
    day12 bash中的if、for
    day11 grep正则匹配
    day10 nfs服务,nginx负载均衡,定时任务
    SpringMVC11文件上传
    SpringMVC10数据验证
    SpringMVC09异常处理和类型转化器
    SpringMVC08转发和重定向
    SpringMVC07处理器方法的返回值
    SpringMVC06以对象的方式获取前台的数据
    SpringMVC05使用注解的方式
  • 原文地址:https://www.cnblogs.com/Jerryshome/p/2417610.html
Copyright © 2011-2022 走看看