Search code examples
pythonstatic-methods

Can I call a static method from outside a class without initializing the class?


class BaseIndicesLinker:

    def __init__(
        self,
        date: int)

    @staticmethod
    def some_static_function(i: int):
        return datetime.datetime(...)



def retrieve_index_codes_from_index_objects(session, date):

    # converting date to expected datetime format
    datetime = some_static_function(date)

    return all_index_codes

The above doesn't work, because some_static_function is 'not defined'.

So I suppose my question is, is it possible to call on the static function without initializing the class BaseIndicesLinker?


Solution

  • Yes, you can call a static method without initializing the class. you just need to use the class name followed by the method name.

    datetime = BaseIndicesLinker.some_static_function(date)