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
Using Property In Python
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.





