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
martineau
  • 119,623
  • 25
  • 170
  • 301
Mike
  • 89
  • 7
  • 1
    I believe you need it to be self.result = Test.test3()+100 – Jlove Dec 03 '21 at 19:26
  • self.result = Test.test3()+100 will not work. the problem comes from c=500+Test.result return c – Mike Dec 03 '21 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. – kaya3 Dec 03 '21 at 19:31
  • I'd refer to this thread on how to properly use classmethod and staticmethod: https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner However beyond that, @kaya3 is right - you have other syntax issues here like the test.test3()+100 line – Jlove Dec 03 '21 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? – Karl Knechtel Dec 03 '21 at 19:34
  • Aside from that, I can't understand what *problem you are trying to solve* with code like this. – Karl Knechtel Dec 03 '21 at 19:35
  • I think result = Test.test3()+100 is defined result. why the result shows result is not defined in c=500+Test.result – Mike Dec 03 '21 at 19:40

1 Answers1

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.

Samwise
  • 68,105
  • 3
  • 30
  • 44