gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:44:11 25 4
gpt4 key购买 nike

我有以下简单的类,想知道是否有一种简单的方法来使用 lambdadecoratorhelper 方法,等等...以避免 CODENAMESALL_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com