mimic
mimic

Reputation: 5224

How to call static method from a static variable inside a class?

I'm trying to implement a simple class with static vars and static methods:

class X(object):
    @staticmethod
    def do_something(par):
        # do something with parameter par
        #...
        return something

    static_var = X.do_something(5) #<-- that's how I call the function

But I have the error NameError: name 'X' is not defined.

How to do call this static function?

Upvotes: 0

Views: 626

Answers (1)

ggorlen
ggorlen

Reputation: 56865

It looks like you'd like to initialize the value of a static class variable using a static function from that same class as it's being defined. You can do this using the following syntax taken from this answer but with an added parameter:

class X:
    @staticmethod
    def do_something(par):
        return par

    static_var = do_something.__func__(5)


print(X.static_var)  # => 5

Referencing a static method of the class X directly inside the X definition fails because X doesn't yet exist. However, since you have defined the @staticmethod do_something, you can call its __func__ attribute with the parameter and assign the result to static_var.

If you're using Python >= 3.10, you don't need the .__func__ property. static_var = do_something(5) will work just fine.

Having said that, more information about the underlying design goal you're trying to implement could reveal a better approach.

Upvotes: 2

Related Questions