How to Write Getter/Setter for Static Variables

In the last post, I blogged about how you should write Getter/Setter for member variables.

This is a follow-up for static variables, instead of instance variables.

I didn’t know the answer to that, until I searched around Stackoverflow. There are a couple of ways around using @property on classmethods.

The best answer for me is this:

1
2
3
4
5
6
7
8
9
10
class MyClass(object):
    _foo = 5
    class __metaclass__(type):
        @property
        def foo(cls):
                return cls._foo

        @foo.setter
        def foo(cls, value):
                cls._foo = value

It uses __metaclass__, some kind of black magic in Python.

With that, you can use the getter/setter on the static variable.

1
2
3
4
5
>>> MyClass.foo
5
>>> MyClass.foo = 3
>>> MyClass.foo
3

Comments