Fredクラスを初期化するコードの一部を読んで、私は以下のapi_key/self.api_keyインタラクションのポイントが不思議でした。 api_keyがクラス定義を参照しているようですが、これはありません... 2つのコメントセクションを参照してください。それだけであればself.api_key is not none: self.api_key=api_key
fred api Python -
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/"""))
最初の3行は削除可能で、self.api_key = api_keyに置き換えられたようですが、それは既にNoneに初期化されているため、次の2つのチェックは必要ありません。右? – Solaxun
これはあなたの質問に書いたものではありませんが、最初の二つの行を 'self.api_key = api_key'で置き換えるとできます。 'Fred(api_key_file =" some_path ")'と書くと、 'self.api_key'が' None'に設定され、それだけです。 'Fred()'と同じです(環境変数を取得する必要があります)。 – zezollo