add a static property to a class in python

To add a static property to a class in Python, you can utilize the @staticmethod decorator in combination with the @property decorator. Here is an example:

main.py
class MyClass:
    my_static_property = "This is a static property"

    @staticmethod
    @property
    def static_property():
        return MyClass.my_static_property
170 chars
8 lines

In the above example, my_static_property is a static attribute of the class MyClass. We then define a @staticmethod with the @property decorator called static_property which simply returns the value of my_static_property.

Now we can access this static property on the class rather than an instance of the class:

main.py
print(MyClass.static_property)  # Output: This is a static property
68 chars
2 lines

gistlibby LogSnag