Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
Letting direct access to an object attributes may be not the best idea. If clients communicate with the object via methods, you can always modify how every request is processed while with direct attribute access it may be not possible. Different languages deal with that problem in different ways. In Ruby, it's syntactically impossible to access an attribute directly, obj.x is a call of the x method. In Java, it's recommended to make all attributes private and write trivial getters instead: public int getX() { return this.x }. Python offers a solution that is somehow similar to that that Ruby has. You can define property so obj.x invokes a method instead of returning the x attribute directly. class Example: def __init__(self, x): self._x = x @property def x(self): return self._x