Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading