根据字符串的值创建变量

Create a variable based on the value of a string

我想根据变量名称列表启动一个class。

澄清一下,这是我的非 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=''))

看起来像您通常使用 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))