我想根据变量名称列表启动一个类。
澄清一下,这是我的非DRY代码:
def __init__(self, page):
self.page_id = page.page_id
self.page_access_token = page.page_access_token
self.page_fans_country = _get(obj=self._request(endpoint='page_fans_country', period=''))
self.page_fans_gender_age = _get(obj=self._request(endpoint='page_fans_gender_age', period=''),)
self.page_impressions = _get(obj=self._request(endpoint='page_impressions', period=''))
self.page_impressions_unique = _get(obj=self._request(endpoint='page_impressions_unique', period=''))
self.page_impressions_by_country_unique = _get(obj=self._request(endpoint='page_impressions_by_country_unique', period=''))
self.page_impressions_by_age_gender_unique = _get(obj=self._request(endpoint='page_impressions_by_age_gender_unique', period=''))
self.page_engaged_users = _get(obj=self._request(endpoint='page_engaged_users', period=''))
self.page_consumptions = _get(obj=self._request(endpoint='page_consumptions', period=''))
self.page_consumptions_unique = _get(obj=self._request(endpoint='page_consumptions_unique', period=''))
它不是DRY - 如果我想更改端点的名称,我需要进行两次更改。
有没有办法执行此操作:
def __init__(self, page):
self.page_id = page.page_id
self.page_access_token = page.page_access_token
list = ['page_fans_country','page_fans_gender_age',(...)]
for element in list:
self.{ var with the name of element } = _get(obj=self._request(endpoint=element, period=''))
答案 0 :(得分:3)
看起来您通常会使用setattr
。然后,您可以使用函数来清除对_get
的详细调用:
class Dry(object):
def __init__(self, page):
...
for item in lst:
setattr(self, item, self.alloc(item))
def alloc(self, endpoint, period=''):
return _get(obj=self._request(endpoint=endpoint, period=period))