How do I create class (i.e. static) variables or methods in Python?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Variables declared inside the class definition, but not inside a method are class or static variables:
As @millerdev points out, this creates a class-level
ivariable, but this is distinct from any instance-levelivariable, so you could haveThis is different from C++ and Java, but not so different from C#, where a static member can’t be accessed using a reference to an instance.
See what the Python tutorial has to say on the subject of classes and class objects.
@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.
@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument.