fred api Python -

时间:2016-04-30 01:10:56

标签: python

通过阅读一些代码来初始化Fred类,我想知道下面的api_key / self.api_key交互有什么意义。似乎api_key引用了类定义,但没有...参见两个注释部分。不应该像self.api_key is not none: self.api_key=api_key

那样
  class Fred(object):
    earliest_realtime_start = '1776-07-04'
    latest_realtime_end = '9999-12-31'
    nan_char = '.'
    max_results_per_request = 1000

    def __init__(self,
                 api_key=None,
                 api_key_file=None):
        """
        Initialize the Fred class that provides useful functions to query the Fred dataset. You need to specify a valid
        API key in one of 3 ways: pass the string via api_key, or set api_key_file to a file with the api key in the
        first line, or set the environment variable 'FRED_API_KEY' to the value of your api key. You can sign up for a
        free api key on the Fred website at http://research.stlouisfed.org/fred2/
        """
        self.api_key = None #why? already is none
        if api_key is not None: #what is this for? 
            self.api_key = api_key
        elif api_key_file is not None:
            f = open(api_key_file, 'r')
            self.api_key = f.readline().strip()
            f.close()
        else:
            self.api_key = os.environ.get('FRED_API_KEY')
        self.root_url = 'https://api.stlouisfed.org/fred'

        if self.api_key is None:
            import textwrap
            raise ValueError(textwrap.dedent("""\
                    You need to set a valid API key. You can set it in 3 ways:
                    pass the string with api_key, or set api_key_file to a
                    file with the api key in the first line, or set the
                    environment variable 'FRED_API_KEY' to the value of your
                    api key. You can sign up for a free api key on the Fred
                    website at http://research.stlouisfed.org/fred2/"""))

1 个答案:

答案 0 :(得分:2)

<强> 1

self.api_key = None #why? already is none

不,它不是None:此Fred实例的api_key属性尚不存在。 api_keyself.api_key不是同一个变量。因此,编写self.api_key = None可确保此属性存在。

<强> 2

if api_key is not None: #what is this for? 

api_keykeyword argument

def __init__(self,
                 api_key=None,
                 api_key_file=None):

因此,当创建新的Fred实例时,可以编写Fred(api_key='something')。在这种情况下,api_key将从'something'开头包含__init__()。但也可以写Fred()api_key默认包含None __init__()开头api_key

如果用户尚未输入api_key_file参数的值,则该函数将检查相同的if self.api_key is not none: self.api_key=api_key 参数。如果未输入任何内容,它将尝试从环境变量中检索它。如果它仍然无法获得任何值,则会引发异常。

3。所以如果你开始编写函数:

AttributeError

您可能会收到self.api_key(因为EditText尚不存在)。