2016-04-30 3 views
0

Fredクラスを初期化するコードの一部を読んで、私は以下のapi_key/self.api_keyインタラクションのポイントが不思議でした。 api_keyがクラス定義を参照しているようですが、これはありません... 2つのコメントセクションを参照してください。それだけであればself.api_key is not none: self.api_key=api_keyfred 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/""")) 

答えて

2

1.

self.api_key = None #why? already is none 

のようなものであるべきではないいいえ、それはなしていないません:このフレッド・インスタンスの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(api_key='something')を書き込むことが可能です。この場合、api_keyは、__init__()の先頭から'something'を含むことになります。ユーザーがapi_key引数の値を入力していない場合でも、それは__init__()

を開始してから、デフォルトでは、NoneFred()api_key含まれていますを書くことも可能なのは、関数が可能api_key_file引数に同じことを確認します。何も入力されていなければ、環境変数から検索しようとします。それでも値を取得できない場合は、例外が発生します。 (まだ存在しないself.api_keyので)AttributeError

if self.api_key is not none: self.api_key=api_key 

あなたはおそらく取得します:

3.は、だから、機能の書き込みを開始します。

+0

最初の3行は削除可能で、self.api_key = api_keyに置き換えられたようですが、それは既にNoneに初期化されているため、次の2つのチェックは必要ありません。右? – Solaxun

+0

これはあなたの質問に書いたものではありませんが、最初の二つの行を 'self.api_key = api_key'で置き換えるとできます。 'Fred(api_key_file =" some_path ")'と書くと、 'self.api_key'が' None'に設定され、それだけです。 'Fred()'と同じです(環境変数を取得する必要があります)。 – zezollo