0

After I ran the code below, I got NameError: name 'result' is not defined. I tried to use class variable in a class method. Why does it give me an error?

class Test():
    def __init__(self):
        self.a=self.test1()
        self.result = Test.test2()+Test.test3()
    def test1(self):
        a=100
        return a

    result = Test.test3()+100
    @classmethod
    def test2(cls):
        b=200
        return b

    @staticmethod
    def test3():
        print("Testing3 is calling ")
        c=500+Test.result
        return c

Error:

result = Test.test3()+100
  File "<ipython-input-29-29d4025016c1>", line 18, in test3
    c=500+result
  NameError: name 'result' is not defined
7
  • 1
    I believe you need it to be self.result = Test.test3()+100 Commented Dec 3, 2021 at 19:26
  • self.result = Test.test3()+100 will not work. the problem comes from c=500+Test.result return c Commented Dec 3, 2021 at 19:27
  • 1
    Test.result is declared in the line result = Test.test3()+100, so how can it be declared at the time Test.test3() is being called? There is a circular reference. Commented Dec 3, 2021 at 19:31
  • I'd refer to this thread on how to properly use classmethod and staticmethod: stackoverflow.com/questions/12179271/… However beyond that, @kaya3 is right - you have other syntax issues here like the test.test3()+100 line Commented Dec 3, 2021 at 19:33
  • In your own words, where you have result = Test.test3()+100, what do you expect that to do, and when? Where you have c=500+Test.result, do you see how that depends on result = Test.test3()+100 having already occurred? Could it have already occurred? Commented Dec 3, 2021 at 19:34

1 Answer 1

1

At the time the line of code in question is evaluated, result is not a class variable. It's been defined as an instance variable here:

    def __init__(self):
        self.a=self.test1()
        self.result = Test.test2()+Test.test3()

but the line of code that defines Test.result as a class variable:

    result = Test.test3()+100

has not yet finished executing at the time that it calls test3(), which itself has a dependency on Test.result.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.