[Python] Accessing static/class members within the class [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    Imagine a simple class like this:

    class MyClass:
    my_var = 'a'

    @staticmethod
    def read_var_static():
    print(MyClass.my_var)

    @staticmethod
    def write_var_static():
    MyClass.my_var += '1'
    print(MyClass.my_var)

    @classmethod
    def read_var_class(cls):
    print(cls.my_var)

    @classmethod
    def write_var_class(cls):
    cls.my_var += '1'
    print(cls.my_var)


    I have tried running the code and played around with different methods in the class. I see that both the class methods and the static counterpart give the same result.

    Am I safe to assume that directly referencing the class members using MyClass.* in static methods is just the same as cls.* in class methods?

    • If so, why choose one over the other?
    • If not, what are the differences?

    I suppose the "@classmethod vs @staticmethod" question has been asked a million times before, but this question is slightly more specific, which I can't find much information on this.

    Continue reading...

Compartilhe esta Página