[Python] Confused about self.var vs self.__class__.var [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I played with some code below:

    class MyClass:
    s_occ = 42
    def __init__(self):
    print( self.s_occ ) # print out 1
    self.s_occ += 1
    print(self.__class__.s_occ) # print out 1

    cls1 = MyClass()


    Given that self.s_occ += 1 does not change self.__class__.s_occ, it seems they are not aliased.

    However, I didn't define self.s_occ, shouldn't it hence be an undefined symbol? Why it seems to be a symbol that has same value as self.__class__.s_occ?

    Continue reading...

Compartilhe esta Página