__add__,关于运算符重载(用户权限)
2024-10-19 16:31:36
1、首先定义三种用户类型:普通用户、管理员、超级管理员,不同用户类型的用户权限关系如下:
先看一段代码:
class Scope(): # 定义一个基类,因为每个权限类都需要add()方法
allow_api = [] def add(self, other):
self.allow_api = self.allow_api + other.allow_api
return self class UserScope(Scope): # 普通用户权限
allow_api = ['权限A'] class AdminScope(Scope): # 管理员权限(管理员权限=管理员权限+普通用户权限)
allow_api = ['权限B'] def __init__(self):
self.add(UserScope()) class SuperScope(Scope): # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
allow_api = ['权限C'] def __init__(self):
self.add(AdminScope()) u = UserScope()
a = AdminScope()
s = SuperScope()
print('普通用户 ',u.allow_api)
print('管理员 ',a.allow_api)
print('超级管理员',s.allow_api)
执行结果:
普通用户 ['权限A']
管理员 ['权限B', '权限A']
超级管理员 ['权限C', '权限B', '权限A']
总结:其实上面代码理解起来也通俗易懂,即使出现重复权限,也可以通过集合单独改造去重,但是这里想升级一下,使用到__add__这个魔法方法
2、升级,改造add()方法:
class Scope(): # 定义一个基类,因为每个权限类都需要add()方法
allow_api = [] def __add__(self, other):
self.allow_api = self.allow_api + other.allow_api
return self class UserScope(Scope): # 普通用户权限
allow_api = ['权限A'] class AdminScope(Scope): # 管理员权限(管理员权限=管理员权限+普通用户权限)
allow_api = ['权限B'] def __init__(self):
self + UserScope() class SuperScope(Scope): # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
allow_api = ['权限C'] def __init__(self):
self + AdminScope() + UserScope() u = UserScope()
a = AdminScope()
s = SuperScope()
print('普通用户 ', u.allow_api)
print('管理员 ', a.allow_api)
print('超级管理员', s.allow_api)
执行结果:
普通用户 ['权限A']
管理员 ['权限B', '权限A']
超级管理员 ['权限C', '权限B', '权限A', '权限A']
效果一样,但是出现了重复权限,所以下一步就是去重:
class Scope(): # 定义一个基类,因为每个权限类都需要add()方法
allow_api = [] def __add__(self, other):
self.allow_api = list(set(self.allow_api + other.allow_api))
return self class UserScope(Scope): # 普通用户权限
allow_api = ['权限A'] class AdminScope(Scope): # 管理员权限(管理员权限=管理员权限+普通用户权限)
allow_api = ['权限B'] def __init__(self):
self + UserScope() class SuperScope(Scope): # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
allow_api = ['权限C'] def __init__(self):
self + AdminScope() + UserScope() u = UserScope()
a = AdminScope()
s = SuperScope()
print('普通用户 ', u.allow_api)
print('管理员 ', a.allow_api)
print('超级管理员', s.allow_api)
执行结果:
普通用户 ['权限A']
管理员 ['权限A', '权限B']
超级管理员 ['权限A', '权限B', '权限C']
总结:其实也就是在遇到“+”这个符号的时候,会调用__add__方法。
效果都是一样的,但是感觉这样才是真正用到python。。。
最新文章
- localStorage的使用
- getRequestURI,getRequestURL的区别
- wamp环境搭建
- 笔记-iOS弹幕(源码)实现原理解析
- Esper系列(八)Method Definition、Schema
- IE10以下placeholder不兼容
- Query插件
- 探索Gallery和ImageSwitcher布局
- eclipse快捷键 自己使用简单总结
- shell运算符之 关系运算符,算数运算符,布尔运算符,字符串运算符和文件测试运算符
- UEP-自定义持久化类
- Django中的F和Q函数
- Could not find a package configuration file provided by ";Qt5Widgets";
- error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
- java 第三周作业
- HashSet的底层
- 【刷题】AtCoder Regular Contest 002
- TF-IDF理解及其Java实现
- fafu 1411
- 【原】解决Debug JDK source 无法查看局部变量的问题方案(重新编译rt.jar包)