首页 > 解决方案 > 对象没有属性,但定义了属性,不确定是否有缩进问题

问题描述

我正在运行的文件 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

标签: python

解决方案


对代码进行一些假设,我认为问题在于类型提示:

-> 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)等等。


推荐阅读