0

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?

14
  • Where do you define par? Commented Nov 23, 2018 at 22:19
  • What are you trying to do? par is a parameter in do_something and you're trying to use par outside of that definition. Commented Nov 23, 2018 at 22:32
  • @RedCricket I don't know where to define it. I hope somebody can help. Commented Nov 23, 2018 at 22:36
  • @ggorlen How to define the ANS properly? I'm trying to call static function from the static variable and definitely I'm not doing properly but I don't know how to do it, that's the question. Commented Nov 23, 2018 at 22:38
  • You are not using par in your method so just get rid of it. Commented Nov 23, 2018 at 22:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.