我有下面这个简单的类,我想知道是否有一个简单的方法来使用lambda
,decorator
,或helper method
,等等。。。要避免在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:
#...
哦,闪亮的:-}
可以在helper方法中使用^{} 来生成名称:
然后你可以改变你的类来利用它:
你也许可以用这样的方法:
相关问题 更多 >
编程相关推荐