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

What is the easiest way to define setter and getter in Python? There is something like in C #

public int Prop {get; set;} 

How to do it? Since writing both the setter and getter methods for a single property like this is 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!

+4
source share
3 answers

If the setter and getter do nothing but access the underlying real attribute, then the easiest way to implement them is not to write setters and getters in general. This is standard behavior, and it makes no sense to write functions that recreate the behavior that the attribute has.

You do not need getters and setters to provide encapsulation in the event that your access logic changes to something other than standard access mechanics, since introducing a property will not violate your interface.

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

+17
source

Usually you don't write setters / getters at all. There is no point, since python does not prevent anyone from accessing attributes directly. However, if you need logic, you can use property s

 class Foo(object): def __init__(self, db): self.db = db @property def x(self): db.get('x') @x.setter def x(self, value): db.set('x', value) @x.deleter def x(self): db.delete('x') 

Then you can use these property methods in the same way as for the base attribute value:

 foo = Foo(db) foo.x foo.x = 'bar' del foo.x 
+7
source

property is a built-in function in Python, see this link for their use. It works without pairs, so you can start with Sven preferences only using the attribute and change it to use getters and setters later.

+1
source

Source: https://habr.com/ru/post/1400027/


All Articles