传递param时Python类调用不起作用

2024-09-30 22:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个类,一切正常,直到我试图通过调用一个变量传递一个参数

让我给你看看:

实例一-直接传递的参数

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'}

实例二-通过变量传递的参数

    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)

我不明白通过外部通话有什么区别。变量使

谢谢大家


Tags: inpyselfdfgetvaluetagline
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:11

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

错误在您处理的数据中-您得到了None的某个地方

如果你使用

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

你会得到同样的错误

问题是,在某个地方你得到了一个None值,并尝试使用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

相关问题 更多 >