Python-传递参数时类调用不起作用

时间:2018-11-18 08:56:10

标签: python python-3.x python-requests

我写了一个类,一切正常,直到我尝试通过调用变量来传递参数为止。

让我告诉你:

实例一-参数直接通过

a = Statements("AAPL","income_statement", "FY", ["2017","2018"])
d = a.get()
print(d)

输出(一切正常):

       [{'tag': 'operatingrevenue', 'value': 229234000000.0}, {'tag': 'totalrevenue', 'value': 229234000000.0}, {'tag': 'operatingcostofrevenue', 'value': 141048000000.0}, {'tag': 'totalcostofrevenue', 'value': 141048000000.0}, {'tag': 'totalgrossprofit', 'value': 88186000000.0}, {'tag': 'sgaexpense', 'value': 15261000000.0}, {'tag': 'rdexpense', 'value': 11581000000.0}, {'tag': 'totaloperatingexpenses', 'value': 26842000000.0}, {'tag': 'totaloperatingincome', 'value': 61344000000.0}, {'tag': 'otherincome', 'value': 2745000000.0}, {'tag': 'totalotherincome', 'value': 2745000000.0}, {'tag': 'totalpretaxincome', 'value': 64089000000.0}, {'tag': 'incometaxexpense', 'value': 15738000000.0}, {'tag': 'netincomecontinuing', 'value': 48351000000.0}, {'tag': 'netincome', 'value': 48351000000.0}, {'tag': 'netincometocommon', 'value': 48351000000.0}, {'tag': 'weightedavebasicsharesos', 'value': 5217242000.0}, {'tag': 'basiceps', 'value': 9.27}, {'tag': 'weightedavedilutedsharesos', 'value': 5251692000.0}, {'tag': 'dilutedeps', 'value': 9.21}, {'tag': 'weightedavebasicdilutedsharesos', 'value': 5215900000.0}, {'tag': 'basicdilutedeps', 'value': 9.27}, {'tag': 'cashdividendspershare', 'value': 2.4}]
{'ticker': 'AAPL', 'statement': 'income_statement', 'type': 'FY', 'fiscal_year': '2017'}
[{'tag': 'operatingrevenue', 'value': 265595000000.0}, {'tag': 'totalrevenue', 'value': 265595000000.0}, {'tag': 'operatingcostofrevenue', 'value': 163756000000.0}, {'tag': 'totalcostofrevenue', 'value': 163756000000.0}, {'tag': 'totalgrossprofit', 'value': 101839000000.0}, {'tag': 'sgaexpense', 'value': 16705000000.0}, {'tag': 'rdexpense', 'value': 14236000000.0}, {'tag': 'totaloperatingexpenses', 'value': 30941000000.0}, {'tag': 'totaloperatingincome', 'value': 70898000000.0}, {'tag': 'otherincome', 'value': 2005000000.0}, {'tag': 'totalotherincome', 'value': 2005000000.0}, {'tag': 'totalpretaxincome', 'value': 72903000000.0}, {'tag': 'incometaxexpense', 'value': 13372000000.0}, {'tag': 'netincomecontinuing', 'value': 59531000000.0}, {'tag': 'netincome', 'value': 59531000000.0}, {'tag': 'netincometocommon', 'value': 59531000000.0}, {'tag': 'weightedavebasicsharesos', 'value': 4955377000.0}, {'tag': 'basiceps', 'value': 12.01}, {'tag': 'weightedavedilutedsharesos', 'value': 5000109000.0}, {'tag': 'dilutedeps', 'value': 11.91}, {'tag': 'weightedavebasicdilutedsharesos', 'value': 4956800000.0}, {'tag': 'basicdilutedeps', 'value': 12.01}, {'tag': 'cashdividendspershare', 'value': 2.72}]
{'ticker': 'AAPL', 'statement': 'income_statement', 'type': 'FY', 'fiscal_year': '2018'}

实例2-参数通过变量传递

    ticker = "MMM"
__________
Class ***:
      class code
__________

e= Statements(ticker,"income_statement","FY", ["2017", "2018"])
f = e.get()
print(e)

输出(不好):

{'ticker': 'MMM', 'statement': 'income_statement', 'type': 'FY', 'fiscal_year': '2017'}
Traceback (most recent call last):
[]
  File "C:/Users/ruleb/Desktop/python test/Ptf_Project/Financials.py", line 96, in <module>
{'ticker': 'MMM', 'statement': 'income_statement', 'type': 'FY', 'fiscal_year': '2018'}
    f = e.get()
  File "C:/Users/ruleb/Desktop/python test/Ptf_Project/Financials.py", line 86, in get
    df = df.applymap(lambda x: x["value"])
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 6072, in applymap
    return self.apply(infer)
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 6014, in apply
    return op.get_result()
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\apply.py", line 318, in get_result
    return super(FrameRowApply, self).get_result()
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\apply.py", line 142, in get_result
    return self.apply_standard()
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\apply.py", line 248, in apply_standard
    self.apply_series_generator()
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\apply.py", line 277, in apply_series_generator
    results[i] = self.f(v)
  File "C:\Users\ruleb\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 6070, in infer
    return lib.map_infer(x.astype(object).values, func)
  File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer
  File "C:/Users/ruleb/Desktop/python test/Ptf_Project/Financials.py", line 86, in <lambda>
    df = df.applymap(lambda x: x["value"])
TypeError: ("'NoneType' object is not subscriptable", 'occurred at index operatingrevenue')

Process finished with exit code 1

我附上完整的代码供您参考:

import requests
import pandas as pd
ticker = "MMM"

class Statements:

    def __init__(self,ticker = "AAPL",statement= "income_statement",period= "FY",fiscal_year = ["2017","2018"]):
        self.ticker = ticker
        self.statement = statement
        self.period = period
        self.fiscal_year = fiscal_year

    # , ticker, statement, period, fiscal_year
    def get(self):
        api_username = 'x'
        api_password = 'x'
        base_url = "https://api.intrinio.com"
        s = []
        for year in self.fiscal_year:
            request_url = base_url + "/financials/standardized"

            query_params = {
            'ticker': self.ticker,
            'statement': self.statement,
            'type': self.period,
            'fiscal_year': year
            }

            response = requests.get(request_url, params=query_params, auth=(api_username, api_password))
            if response.status_code == 401: print("Unauthorized! Check your username and password."); exit()
                data = response.json()["data"]
                s.append(data)
                print(data)
                print(query_params)

        df = pd.DataFrame(s, index = self.fiscal_year)
        df.columns = [i["tag"] for i in df.iloc[0].values]
        df = df.applymap(lambda x: x["value"])
        # print(df)
        return df


a = Statements("AAPL","income_statement", "FY", ["2017","2018"])
d = a.get()
print(d)

e= Statements(ticker,"income_statement","FY", ["2017", "2018"])
f = e.get()
print(f)

我不知道通过外部呼叫有什么区别。可变品牌。

谢谢大家!

1 个答案:

答案 0 :(得分:1)

您的假设是错误的,不是导致该错误的外部变量。您正在查询不同的代码:"AAPL""MMM"

错误在于您处理的数据中-None在某个地方。

如果您使用

e = Statements("MMM","income_statement","FY", ["2017", "2018"])

您将收到相同的错误。

问题在于,您在某个地方获得了None值并尝试使用None[...]-但没有一个是不能下标的。

调试这些行:

data = response.json()["data"]                       # json result might be None ?
df.columns = [i["tag"] for i in df.iloc[0].values]   # i might be None
df = df.applymap(lambda x: x["value"])               # x might be None