我目前在python(django)函数中有一堆语言检查:
def __get__(self, instance, owner):
if translation.get_language() == 'fr':
trans_field = getattr(instance, self.fr_field)
else:
return getattr(instance, self.en_field)
我想要做的是循环运行:
for language in languages:
if translation.get_language() == language:
return getattr(instance, self.[language]_field)
else:
return getattr(instance, self.en_field)
我该怎么做?显然self.[language]_field
是伪代码
答案 0 :(得分:2)
你已经有了解决方案。使用getattr
getattr(instance, getattr(self, language + '_field'))
答案 1 :(得分:2)
第二次使用getattr
:
return getattr(instance, gettattr(self, '{}_field'.format(language))