0

I am trying to call a class variable within a staticmethod, but when I called I am getting an error "hello" is not defined. any advise ?

class hello:
    random1 = []

    @staticmethod
    def sub(x):
        hello.random1.append(x -1)

    sub.__func__(2)

if __name__ == "__main__":
    print(hello.random1)
1
  • Yes, because the class hello doesn't exist when it's class body is being executed Commented Nov 23, 2020 at 17:34

1 Answer 1

1

hello doesn't exist as a global name until you dedent out of the class definition (at which point the class is created and assigned to the global name hello). Change the code to:

class hello:
    random1 = []

    @staticmethod
    def sub(x):
        hello.random1.append(x -1)

hello.sub(2)

so sub is invoked after hello exists, and it will work.

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.