<p>我有下面这个简单的类,我想知道是否有一个简单的方法来使用<code>lambda</code>,<code>decorator</code>,或<code>helper method</code>,等等。。。要避免在<code>CODENAMES</code>和<code>ALL_DEFAULTS</code>的每个方法中出现重复的<em>for循环</em>?你知道吗</p>
<pre><code>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
</code></pre>
<p>重复for循环是每个方法的此部分:</p>
<pre><code># ...
for p in cls.PERMS:
for m in cls.MODELS:
#...
</code></pre>