Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Property In Python

DZone's Guide to

Using Property In Python

·
Free Resource
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.
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}