python - 对象没有属性,但定义了属性,不确定是否有缩进问题
问题描述
我正在运行的文件 example_market_data.py,
from marketplace_python.marketplace import Marketplace
marketplace = Marketplace('MY_API_KEY', 'MY_SECRET_KEY')
print(marketplace.ticker('btcmyr'))
print(marketplace.orderbook('btcmyr'))
print(marketplace.get_recent_trades('btcmyr', 1, 10))
和导入的文件,marketplace.py,
from .market_data import MarketData
class Marketplace(MarketData):
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
def orderbook(self, pair: str) -> Dict(str, any):
return MarketData.orderbook(self, pair)
def ticker(self, pair: str) -> Dict(str, any):
return MarketData.ticker(self, pair)
def get_recent_trades(self, pair: str, page: int, per_page: int, sort: str = 'asc'):
return MarketData.get_recent_trades(self, pair, page, per_page, sort)
当我运行 main.py 时,我得到了
AttributeError: 'Marketplace' object has no attribute 'orderbook'
.
我不确定这是否是缩进错误,因为我已经尝试重新排序函数,例如在和其他重新排序样式ticker
之上,但我仍然遇到相同的错误。orderbook
我很确定没有缩进错误,因为我的缩进都是空格。
我错过了什么吗?
编辑:我的项目目录是
marketplace-python
-- examples
---- example_market_data.py
-- marketplace_python
---- marketplace.py
---- market_data.py
解决方案
对代码进行一些假设,我认为问题在于类型提示:
-> Dict(str, any):
应该-> Dict[str, any]:
带方括号。
我想出了
from typing import Dict
class MarketData():
def orderbook(self, pair) -> Dict[str, any]:
pass
def ticker(self, pair) -> Dict[str, any]:
pass
def get_recent_trades(self, pair, page, per_page, sort):
pass
class Marketplace(MarketData):
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
def orderbook(self, pair: str) -> Dict[str, any]:
return MarketData.orderbook(self, pair)
def ticker(self, pair: str) -> Dict[str, any]:
return MarketData.ticker(self, pair)
def get_recent_trades(self, pair: str, page: int, per_page: int, sort: str = 'asc'):
return MarketData.get_recent_trades(self, pair, page, per_page, sort)
marketplace = Marketplace('MY_API_KEY', 'MY_SECRET_KEY')
print(marketplace.ticker('btcmyr'))
print(marketplace.orderbook('btcmyr'))
print(marketplace.get_recent_trades('btcmyr', 1, 10))
这不会崩溃。
您可能可以使用类似的代码。
另一方面,使用以下代码可以更具可读性super()
:
例如,return MarketData.orderbook(self, pair)
作为MarketData
单个超类,转换为return super().orderbook(pair)
等等。
推荐阅读
- r - R data.table 用 SD 排序
- ios - 如何在 React Native 中使用委托?
- angular - 使用动态反应形式(while 中的字段)
- promise - 为什么我的 promise.all 不返回数据,即使它有效
- fuse - 如何知道熔断的请求是否拥塞
- python - 合并具有相同值的行 Pandas
- discord.py - Discord.py role.kick_members 有问题,我得到一个错误
- c# - 实体框架:无法在计算字段 IQueryable 上调用 .OrderBy
- android - 如果记录器显示正文中的对象,为什么要改造 response.body() 返回 null?
- python - Path to stat module via dict variable