我在創建 python 類和方法時遇到了一些麻煩,我不知道如何解決它。
我有 2 個檔案,1 個檔案包含一個具有多種方法的類。其中2個是:
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從另一個檔案訪問時,它現在要求 2 個引數:self 和 tickers。但是,我不需要它是一個實體,所以有沒有辦法將它轉換為靜態方法,同時仍然能夠訪問其他函式?
uj5u.com熱心網友回復:
是的。你可以使用@staticmethod.
正如我在您的get_price_of方法中看到的那樣,您的實體不需要存在。您只需通過 aticker并回傳結果。與get_price_of_list. 它們是恰好位于類命名空間內的實用函式。您也可以在模塊中定義它們。但是在類中使用它們的一個優點是它們現在是有組織的。在類命名空間中積累的相關函式。
將您的方法更改為:
@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] = <CLASS_NAME>.get_price_of(ticker)
return prices
請注意,我self在get_price_of_list.
uj5u.com熱心網友回復:
事情是這樣的:
如果你想讓它成為一個實體。首先,啟動類(傳入類中的所有引數)。然后您可以繼續使用這些功能。此外,您的get_price_of()函式缺少self作為第一個引數,這就是為什么我認為這種方法在作業中失敗的原因。
或者
您可以簡單地使它們成為獨立的功能并洗掉 self. 然后,在一個函式中,您可以簡單地傳遞另一個函式的引數。
這是代碼:
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(tickers):
prices = {}
for ticker in tickers:
prices[ticker] = get_price_of(ticker)
return prices
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532187.html
標籤:Python班级哎呀方法
