我有以下简单的类,我想知道是否有使用一个简单的办法lambda,decorator或者helper method,等...避免重复的循环,在每个方法出现在CODENAMES和ALL_DEFAULTS?
class classproperty(object):
"""
When used to decorate a method in a class, that method will behave
like as a class property.
"""
def __init__(self, f):
# f - the func that's being decorated
self.f = f
def __get__(self, obj, cls):
# call the func on the class
return self.f(cls)
class PermissionInfo(object):
MODELS = ['ticket', 'person', 'role']
PERMS = ['view', 'add', 'change', 'delete']
@classproperty
def CODENAMES(cls):
codenames = []
for p in cls.PERMS:
for m in cls.MODELS:
codenames.append('{}_{}'.format(p, m))
return codenames
@classproperty
def ALL_DEFAULTS(cls):
ret = {}
for p in cls.PERMS:
for m in cls.MODELS:
ret["{}_{}".format(p, m)] = False
return ret
Run Code Online (Sandbox Code Playgroud)
复制for循环是每个方法的这一部分:
# ...
for p in cls.PERMS:
for m in cls.MODELS:
#...
Run Code Online (Sandbox Code Playgroud)
您可以itertools.product在辅助方法中使用以生成名称:
from itertools import product
def names(cls):
yield from ('_'.join(x) for x in product(cls.PERMS, cls.MODELS))
Run Code Online (Sandbox Code Playgroud)
然后你可以改变你的类来使用它:
@classproperty
def CODENAMES(cls):
return list(names(cls))
@classproperty
def ALL_DEFAULTS(cls):
return dict.fromkeys(names(cls), False)
Run Code Online (Sandbox Code Playgroud)