Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: why getter & setter? how can I set attribute quickly? [duplicate]

Possible Duplicate:
What is the benefit to using a ‘get function’ for a python class?

I just started to read Python, but I wonder why does Python need setter and getter at all? it already have object variables which act like property

Consider

class C(object):
    def _init_(self):
        self._x = None

    def get_x(self):
        return self._x

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

Can we just use C.x = "value" to do what we want to do here? what is the benefit of property?

BTW, creating property/setter/getter in this way is cumbersome to me, is there any way to simplify this? like

class C()
   has_attributes("x", "y", "z")
like image 432
woosley. xu Avatar asked Sep 14 '26 00:09

woosley. xu


1 Answers

You can use a property to obtain what you want:

class C(object):
    def _init_(self):
        self._x = None
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

Then you can access the attribute with the usual attribute syntax:

c = C()
c.x = 10    #calls the setter
print(c.x)  #calls the getter

There are some reasons to use a property instead of a plain data attribute:

  • You can document the attribute
  • You can control the access to the attribute, either by making it read-only or by checking the type/value being set
  • You do not break backwards compatibility: if something was a plain instance attribute and then you decide to transform it into a property the code that worked with the attribute will still work. If you used get/set explicit methods all the code that used the old API would have to change
  • It's more readable then using explicit get/set methods.
like image 98
Bakuriu Avatar answered Sep 15 '26 14:09

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!