【问题标题】:Is there a way to access a python method in another file that is reliant on another method without specifying self?有没有一种方法可以访问另一个文件中的 python 方法,该文件依赖于另一个方法而不指定 self?
【发布时间】:2022-11-13 18:23:06
【问题描述】:
我在创建 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。但是,我不需要它是一个实例,所以有没有办法将它转换为静态方法,同时仍然能够访问其他函数?
【问题讨论】:
标签:
python
class
oop
methods
【解决方案1】:
事情是这样的:
如果你想让它成为一个实例。一、开课(传入类中的所有参数).然后您可以继续使用这些功能。此外,您的 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
【解决方案2】:
是的。你可以使用@staticmethod。
正如我在您的 get_price_of 方法中看到的那样,您的实例不需要存在。你只需传递一个ticker,你就会得到一个结果。与get_price_of_list 相同。它们是恰好位于类命名空间内的实用函数。您也可以在模块中定义它们。但是使用@staticmethod 的一个优点是它们现在被组织成一个类。您可以通过类名调用它们。
将您的方法更改为:
@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 中的类名本身。