简体   繁体   中英

Python init doesn't see class variable

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

'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).

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM