在python中使用lambda或helper方法以避免循环重复

时间:2016-12-13 01:11:49

标签: python lambda

我有以下简单的类,我想知道是否有一种简单的方法可以使用lambdadecoratorhelper method等来避免重复的CODENAMES和ALL_DEFAULTS

中的每个方法中显示的> for loop
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:
#...

3 个答案:

答案 0 :(得分:5)

您可以在帮助方法中使用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)

答案 1 :(得分:0)

你可以使用类似的东西:

MODEL_PERMS = list(map(lambda t: "{}_{}".format(t[0],t[1]), itertools.product(MODELS, PERMS)))

答案 2 :(得分:0)

from itertools import product


class PermissionInfo(object):

    MODELS = ['ticket', 'person', 'role']
    PERMS = ['view', 'add', 'change', 'delete']
    PRODUCT = product(PERMS, MODELS)
    CODENAMES = ['{}_{}'.format(p, m) for (p, m) in PRODUCT]
    ALL_DEFAULTS = {codename: False for codename in CODENAMES}
哦,闪亮: - }