Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to define setter and getter in Python

What is the simplest way to define setter and getter in Python? Is there anything like in C#

public int Prop {get; set;}

How to make it like this? Since to write both setter and getter methods for one property like this is just too much work.

class MyClass():
    def foo_get(self):
        return self._foo

    def foo_set(self, val):
        self._foo = val

    foo = property(foo_get, foo_set)

Thanks in advance!

like image 599
zs2020 Avatar asked Mar 06 '12 14:03

zs2020


People also ask

How do you define getter and setter?

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 is the pythonic way to write getters and setters in python?

(Each decorator usage copies and updates the prior property object, so note that you should use the same name for each set, get, and delete function/method.) You should avoid this: def set_property(property,value): def get_property(property):


1 Answers

If the setter and getter do nothing else than accessing an underlying real attribute, then the simplest way of implementing them is not to write setters and getters at all. This is the standard behaviour, and there is no point in writing functions recreating the behaviour the attribute has anyway.

You don't need getters and setters to ensure encapsulation in the case your access logic changes to something different than the standard access mechanics later, since introducing a property won't break your interface.

Python Is Not Java. (And not C# either, for that matter.)

like image 86
Sven Marnach Avatar answered Nov 15 '22 08:11

Sven Marnach