How You Should Write Getter/setter for Python

Coming from the Java world, I am used to writing getter/setter for every member variables that I want to expose. (truth is I made use of IDE to auto generate)

I hate how much code Java has.

With it’s philosophy of readable code, Python is different.

Getter

To write a getter for this member foo:

1
2
3
4
5
6
7
8
class MyClass(object):
  
  def __init__(self):
      self._foo = 1

  @property
  def foo(self):
      return self._foo

It uses an annotation @property. Then to access the property:

1
2
3
my_class = MyClass()
print my_class.foo
# 1

Setter

To set a memter, use the annotation @foo.setter (replace foo with your member name).

1
2
3
4
5
6
class MyClass(object):
  ...

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

Comments