2 Answers
+ 7
use property decorator:
class A:
_a_variable = 1
@property
def a_variable(self):
return self._a_variable
@a_variable.setter
def a_variable(self,value):
self._a_variable = value
This is used for when you want some code to execute when a class attribute is changed. using getters and setters isn't required. if you want to access and change an attribute, just use dot notation.
a = A()
#get variable:
x = a._a_variable
#set variable:
a._a_variable = 2
0
In Python getters and setters aren't really pythonic. Considering that encapsulation in Python isn't really heavily emphasized. If you need to alter your data use the constructor or change it via dot notation. Also you could try to look into properties. Google search my friend.