我必须编写很多Python代码,如下所示:
class MyClass(object):
...
...
...
def handle_request(self, request):
attr1 = self.__get_attr1(request)
self.__validate_attr1(attr1)
attr2 = self.__get_attr2(request)
self.__validate_attr2(attr2)
attr3 = self.__get_attr3(request)
self.__validate_attr1(attr3)
...
...
...
attrn = self.__get_attrn(request)
self.__validate_attrn(attr1)
为了让我的生活更轻松,我想我可以做到以下几点:
class MyClass(object):
...
...
...
def handle_request(self, request):
attr_list = ('attr1', 'attr2', 'attr3', ..., 'attrn');
for a in attr_list:
locals()[a] = eval('self.__get_{}(request)'.format(a))
eval('self.__validate_{}'.format(a)
然而,当我运行此代码时,我收到以下错误:
AttributeError: 'MyClass' object has no attribute '__get_attr1'
显然,我错过了一些很大的东西,但我不确定到底是什么。
答案 0 :(得分:0)
要回答您没有提出的问题,而不是使用eval
,您可能会尝试类似
class MyClass(object):
...
def __init__(self):
self.attr_list = [self.__get_attr1, ..., self.__get_attrn]
self.validate_list = [self.__validate_attr1, ..., self.__validate_attrn]
...
def handle_request(self, request):
attrs = [get(request) for get in self.attr_list]
for validate in self.validate_list:
validate(request)