我有以下简单的类,我想知道是否有一种简单的方法来使用 lambda
、decorator
或 helper 方法
,等等...以避免在 CODENAMES
和 ALL_DEFAULTS
中的每个方法中出现重复的 for 循环?
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
重复的 for 循环是每个方法的这一部分:
# ...
for p in cls.PERMS:
for m in cls.MODELS:
#...
最佳答案
您可以使用 itertools.product
在辅助方法中生成名称:
from itertools import product
def names(cls):
yield from ('_'.join(x) for x in product(cls.PERMS, cls.MODELS))
然后你可以更改你的类来使用它:
@classproperty
def CODENAMES(cls):
return list(names(cls))
@classproperty
def ALL_DEFAULTS(cls):
return dict.fromkeys(names(cls), False)
关于python - 在Python中使用lambda或helper方法来避免for循环重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41112251/