执行main()时触发AttributeError错误,如何修复?
问题分析与解决
错误根源
你在main函数里创建user = stocks(ticker)实例后,错误地通过类本身调用了实例方法stocks.get_price(ticker)。实例方法的第一个参数self需要接收类的实例对象,而你传了字符串ticker,导致self变成了字符串类型,自然没有_price属性,触发了AttributeError。
修正步骤
- 用实例调用方法:创建
user实例后,应该通过user.get_price()获取价格,不需要额外传参数 - 移除无效导入:
from stocks import stocks完全多余,因为stocks类就在当前文件里,这会引发循环导入问题 - 修正缩进问题:原代码
main函数内部缩进混乱,Python对缩进要求严格,必须统一层级
修正后的完整代码
""" This will import yahoo finance api to grab information and sort through 50 different stocks """ from yahoo_fin.stock_info import * class stocks(): """ Class stocks performs functions from the yahoo_fin package """ # Annotate variables _ticker: str _price: float def __init__(self, ticker: str) -> None: """ Initializes the parameters """ self._ticker = ticker self._price = get_live_price(ticker) def __str__(self) -> str: """ Returns a string version of the object """ return f"{self._ticker}, {self._price}" def get_ticker(self) -> str: """ Returns the ticker """ return self._ticker def get_price(self) -> float: """ Returns the price """ return self._price """ Testing the import openpyxl module """ # Imports from openpyxl and openpyxl.utils from openpyxl import Workbook, load_workbook from openpyxl.utils import get_column_letter def main(): # Accessing excel sheet using load_workbook wb = load_workbook('Stocks.xlsx') ws = wb.active # Asks the user to enter a ticker of a company ticker = input("Please enter a ticker for a company: ") user = stocks(ticker) # 通过实例调用get_price方法 price = user.get_price() # Adds titles to columns ws['A1'] = "Ticker" ws['B1'] = "Live Price" # Modifies the cells to display information and tidy up the appearance ws['A2'] = user.get_ticker().upper() ws['B2'] = float("{:.2f}".format(price)) # Saves the document at the end of the code to update the actual excel sheet wb.save('Stocks.xlsx') main()
额外优化点
- Excel单元格可以直接用
ws['A1']这种格式访问,没必要写ws['A' + str(1)] - 原代码中
for row in range(2, 3)循环只执行一次,直接访问A2和B2更简洁
内容的提问来源于stack exchange,提问作者Heartsbane
相关产品推荐
相关产品推荐

