DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Using Property In Python

12.09.2005
| 38452 views |
  • submit to reddit
        In python, you don't need unnecessary getter and setter.
You can get the same thing in a more beautiful way with property.
Initially, you can code
class C(object):
  def __init__(self, x):
    self.x = x

obj = C(5)
obj.x = 6    # set
print obj.x  # get
Later, you can change it to allow getter, setter
class C(object):
  def __init__(self, x):
    self._x = x

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x
  x = property(get_x, set_x)

obj = C(5)
obj.x = 6    # set
print obj.x  # get
You can use class C in almost the same way, but you
can add anything else you want to do to get_x, set_x.