Skip to content
Advertisement

How can I implement a static attribute in Python?

How can I implement a static property or method-pair in Python using a sharable and accessible static attribute?

JavaScript

Output:

JavaScript

Edit: The above source code has a typo in set(). If that typo is fixed, the code runs perfectly.

However, in the case of my original source code, that attribute was a List[str]. In that case, the program only runs only if the attribute is initialized through a pair of square brackets [].

JavaScript

Advertisement

Answer

It would be a better idea is to initialize the class static variable, not just declare its type. This way you would be able to call get even before set, and have it return a default value:

JavaScript

Also, it seems like your original code had a typo, as a result of which set method was assigning to a variable other than the one you were declaring (__static_class instead of __static_attr). Because of that, and because the static variable was not initialized, your get method failed.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement