Is there a way to access a python method in another file that is reliant on another method without specifying self?

Question:

I have some trouble with creating a python class and methods, and I don’t know how to resolve it.

I have 2 files, 1 file contains a class with multiple methods. 2 of these are:

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

So the get_price_of_list method utilises the get_price_of method.

My problem: When accessing the get_price_of_list from another file it now asks for 2 params: self and tickers. However, I don’t need it to be an instance so is there any way to convert it to a static method while still being able to access the other function?

Asked By: Jan Arend

||

Answers:

Here’s the thing:

If you want it to be an instance. First, initiate the class (pass in all args in the class). Then you can continue using the functions. Also, your get_price_of() function is missing self as the first parameter, which is why I suppose this approach fails at work.

OR

You can simply make them independent functions and remove self. Then, inside one function you can simply pass the parameter of the other.

Here’s the code:

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
Answered By: The Myth

Yes. you can use @staticmethod.

As I can see in your get_price_of method, there is no need for your instance to be exist. You just pass a ticker and you get a result back. Same thing with get_price_of_list. They are kind of utility functions that happen to be inside the class namespace. You could also define them in module. But one advantage of using them inside a class is that they are now organized. Relevant functions accumulated inside a class namespace.

Change your methods to:

    @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

Note that I changed self to the class name itself in get_price_of_list.

Answered By: S.B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.