st_bones
st_bones

Reputation: 129

Python:Error calling class variable in a staticmethod

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)

Upvotes: 0

Views: 32

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155674

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.

Upvotes: 1

Related Questions