-1

I'm feeling more dumb than usual, sorry. Can someone put me out of my misery and explain why __init__ can't see class variable s?

Thanks.

class C:
    s = "but why"

    def __init__(self):
        print(s)

c = C()   
#global DEFAULT_STRING = "(undefined)"

Error

Traceback (most recent call last):
    File "/Users/pvdl/Desktop/FH.sp18python/hw/7/test5.py", line 7, in module
    c = C()
    File "/Users/pvdl/Desktop/FH.sp18python/hw/7/test5.py", line 5, in __init__
    print(s)
NameError: name 's' is not defined

Process finished with exit code 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Peter vdL
  • 4,953
  • 10
  • 40
  • 60

2 Answers2

2

's' is declared as class level variable. It is similar to static variable in JAVA. Variable 's' will be shared by all instances of class C. Hence it can be also accessed using class name(C in this case).

Bkmm3
  • 78
  • 6
1

You need to use self, or the class name, to access the class variable s

class C:
    s = "but why"

    def __init__(self):
        print(C.s, self.s)


if __name__ == '__main__':

    c = C()
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80