Using Property In Python
Join the DZone community and get the full member experience.Join For Free
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 # getLater, 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 # getYou can use class C in almost the same way, but you can add anything else you want to do to get_x, set_x.
Opinions expressed by DZone contributors are their own.