__add__,关于运算符重载(用户权限)

1、首先定义三种用户类型:普通用户、管理员、超级管理员,不同用户类型的用户权限关系如下:



先看一段代码:
 1 class Scope():  # 定义一个基类,因为每个权限类都需要add()方法
 2     allow_api = []
 3 
 4     def add(self, other):
 5         self.allow_api = self.allow_api + other.allow_api
 6         return self
 7 
 8 
 9 class UserScope(Scope):  # 普通用户权限
10     allow_api = ['权限A']
11 
12 
13 class AdminScope(Scope):  # 管理员权限(管理员权限=管理员权限+普通用户权限)
14     allow_api = ['权限B']
15 
16     def __init__(self):
17         self.add(UserScope())
18 
19 
20 class SuperScope(Scope):  # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
21     allow_api = ['权限C']
22 
23     def __init__(self):
24         self.add(AdminScope())
25 
26 
27 u = UserScope()
28 a = AdminScope()
29 s = SuperScope()
30 print('普通用户  ',u.allow_api)
31 print('管理员    ',a.allow_api)
32 print('超级管理员',s.allow_api)

执行结果:
普通用户   ['权限A']
管理员     ['权限B', '权限A']
超级管理员 ['权限C', '权限B', '权限A']

总结:其实上面代码理解起来也通俗易懂,即使出现重复权限,也可以通过集合单独改造去重,但是这里想升级一下,使用到__add__这个魔法方法

2、升级,改造add()方法:

 1 class Scope():  # 定义一个基类,因为每个权限类都需要add()方法
 2     allow_api = []
 3 
 4     def __add__(self, other):
 5         self.allow_api = self.allow_api + other.allow_api
 6         return self
 7 
 8 
 9 class UserScope(Scope):  # 普通用户权限
10     allow_api = ['权限A']
11 
12 
13 class AdminScope(Scope):  # 管理员权限(管理员权限=管理员权限+普通用户权限)
14     allow_api = ['权限B']
15 
16     def __init__(self):
17         self + UserScope()
18 
19 
20 class SuperScope(Scope):  # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
21     allow_api = ['权限C']
22 
23     def __init__(self):
24         self + AdminScope() + UserScope()
25 
26 
27 u = UserScope()
28 a = AdminScope()
29 s = SuperScope()
30 print('普通用户  ', u.allow_api)
31 print('管理员    ', a.allow_api)
32 print('超级管理员', s.allow_api)

执行结果:

普通用户   ['权限A']
管理员     ['权限B', '权限A']
超级管理员 ['权限C', '权限B', '权限A', '权限A']

效果一样,但是出现了重复权限,所以下一步就是去重:

 1 class Scope():  # 定义一个基类,因为每个权限类都需要add()方法
 2     allow_api = []
 3 
 4     def __add__(self, other):
 5         self.allow_api = list(set(self.allow_api + other.allow_api))
 6         return self
 7 
 8 
 9 class UserScope(Scope):  # 普通用户权限
10     allow_api = ['权限A']
11 
12 
13 class AdminScope(Scope):  # 管理员权限(管理员权限=管理员权限+普通用户权限)
14     allow_api = ['权限B']
15 
16     def __init__(self):
17         self + UserScope()
18 
19 
20 class SuperScope(Scope):  # 超级管理员(超级管理员权限=超级管理员权限+管理员权限+普通用户权限)
21     allow_api = ['权限C']
22 
23     def __init__(self):
24         self + AdminScope() + UserScope()
25 
26 
27 u = UserScope()
28 a = AdminScope()
29 s = SuperScope()
30 print('普通用户  ', u.allow_api)
31 print('管理员    ', a.allow_api)
32 print('超级管理员', s.allow_api)

执行结果:

普通用户   ['权限A']
管理员     ['权限A', '权限B']
超级管理员 ['权限A', '权限B', '权限C']

总结:其实也就是在遇到“+”这个符号的时候,会调用__add__方法。
   效果都是一样的,但是感觉这样才是真正用到python。。。

  

猜你喜欢

转载自www.cnblogs.com/MisterZZL/p/9860585.html