+-
python – 配置tkinter小部件时出错:’NoneType’对象没有属性
我运行下面的代码,当我硬编码值时运行正常

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'

请帮忙

最佳答案
NoneType对象没有属性…意味着您有一个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())
点击查看更多相关文章

转载注明原文:python – 配置tkinter小部件时出错:’NoneType’对象没有属性 - 乐贴网