如何将Python类方法转为静态方法并调用同类其他方法?
解决Python类方法转静态方法并保持依赖调用的问题
现有一个Python类包含两个方法:
def get_price_of(ticker: str) -> float: URL = 'https://api.kucoin.com/api/v1/market/orderbook/level1?symbol=' r = requests.get(URL + ticker).json() return r['data']['price'] def get_price_of_list(self, tickers): prices = {} for ticker in tickers: prices[ticker] = self.get_price_of(ticker) return prices
get_price_of_list方法依赖get_price_of,现在不想实例化类就能调用get_price_of_list,同时保留两个方法的调用关系,可按以下方式调整:
解决方案:将两个方法都转为静态方法
给两个方法加上@staticmethod装饰器,同时修改get_price_of_list内部的调用方式,直接通过类名调用get_price_of:
import requests class PriceFetcher: @staticmethod def get_price_of(ticker: str) -> float: URL = 'https://api.kucoin.com/api/v1/market/orderbook/level1?symbol=' r = requests.get(URL + ticker).json() return r['data']['price'] @staticmethod def get_price_of_list(tickers): prices = {} for ticker in tickers: prices[ticker] = PriceFetcher.get_price_of(ticker) return prices
调用方式
在其他文件中直接通过类名调用,无需实例化:
from your_module import PriceFetcher result = PriceFetcher.get_price_of_list(["BTC-USDT", "ETH-USDT"]) print(result)
说明
@staticmethod装饰器会将方法标记为静态方法,这类方法不需要self参数,也不依赖类的实例状态。- 把
self.get_price_of(ticker)改成PriceFetcher.get_price_of(ticker),就能在静态方法里调用另一个静态方法,保持原有的依赖逻辑。
内容的提问来源于stack exchange,提问作者Jan Arend
相关产品推荐
相关产品推荐

