【问题标题】:Error when configuring tkinter widget: 'NoneType' object has no attribute配置 tkinter 小部件时出错:“NoneType”对象没有属性
【发布时间】:2015-06-27 13:57:29
【问题描述】:

我正在运行下面的代码,当我对值进行硬编码时运行良好

from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote('INFY')
        print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')

看到我已经硬编码了值 nse.get_quote('INFY') 但是当我运行以下代码时,出现以下错误:

from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote(stock)
        print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')

错误:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')
AttributeError: 'NoneType' object has no attribute 'get'

请帮忙

【问题讨论】:

  • q = nse.get_quote(stock) 返回无。检查哪些 nse_stocks 可用。
  • all_nse_stocks 长什么样子?
  • all_nse_stocks 是一个包含 INFY 的文件

标签: python nonetype


【解决方案1】:

请检查“库存”的类型 q = nse.get_quote(股票)

它必须是一个字符串。此外,nestools 仅在 Python2 上受支持,您尚未说明您的 Python 版本。

如果您在阅读本文时仍然遇到问题,请告诉我。

【讨论】:

    【解决方案2】:

    NoneType object has no attribute ... 表示您有一个 None 对象,并且您正在尝试使用该对象的属性。

    在你的情况下,你正在做q.get(...),所以q 必须是None。由于q 是调用nse.get_quote(...) 的结果,因此该函数必须有可能返回None。您需要调整代码以考虑这种可能性,例如在尝试使用之前检查结果:

    q = nse.get_quote(stock)
    if q is not None:
        print ...
    

    问题的根源可能在于您阅读文件的方式。 stock 将包含换行符,因此您应该在调用 nse.get_quote 之前将其去掉:

    q = nse.get_quote(stock.strip())
    

    【讨论】:

    • 你好 Bryan,我在 all_nse_stocks 中只有一个值,即 INFY。如果我硬编码,那么我得到正确的输出。问题只是当我从文件中读取值时
    • @user3198755:你试过any调试吗?例如,在获取报价之前打印出stock 的值。
    • 是的,在 for 循环之后,我尝试打印股票值,它给出了正确的值,即 INFY
    • @user3198755: 你确定是INFY 而不是INFY&lt;newline&gt;?它可能有一个换行符,您需要将其剥离。我已经更新了我的答案以说明如何。
    • 我已经仔细检查过了。它最后没有任何换行符。 nse.get_quote('INFY') 有效,但 nse.get_quote(stock) 无效。它与单引号有什么关系吗? INFY 和“INFY”?
    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多