Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the pythonic way to use getters and setters?

I'm doing it like:

def set_property(property,value):   def get_property(property):   

or

object.property = value   value = object.property 

I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.

like image 355
Jorge Guberte Avatar asked Apr 13 '10 04:04

Jorge Guberte


People also ask

How do you use getters and setters?

The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.

What can I use instead of getters and setters?

You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use.

What are the benefits of using getter and setter methods?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.

Do Python classes need getters and setters?

Let's write the same implementation in a Pythonic way. You don't need any getters, setters methods to access or change the attributes. You can access it directly using the name of the attributes.


1 Answers

Try this: Python Property

The sample code is:

class C(object):     def __init__(self):         self._x = None      @property     def x(self):         """I'm the 'x' property."""         print("getter of x called")         return self._x      @x.setter     def x(self, value):         print("setter of x called")         self._x = value      @x.deleter     def x(self):         print("deleter of x called")         del self._x   c = C() c.x = 'foo'  # setter called foo = c.x    # getter called del c.x      # deleter called 
like image 81
Grissiom Avatar answered Sep 21 '22 07:09

Grissiom