Setter and Getter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson

Setter and Getter

are setter and getter keywords here? if so, then why are we writing code under them? I can write @xyz.setter and write the code to get the value rather than setting. Whats the difference?

18th Feb 2017, 11:46 PM
Vamsi Mohan Ramineedi
Vamsi Mohan Ramineedi - avatar
2 Answers
+ 8
Getters and setters aren't very pythonic because encapsulation isn't such a big deal in python. What setters do in python is run code when the value is changed. E.g: class A: _x = 2 @property def x(self): return _x @x.setter def x(self,arg) self._x = arg print("ham") a = A() a.x = 11 #output: ham regularly getting and setting attributes is as easy as: #Get x a_variable = a.x #Set x a.x = 3
19th Feb 2017, 1:45 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 2
That special function will be called whenever you use "=" so it is useful to write code that sets the given value. So, whenever you do anything like"egg" the setter function will be called with the "egg" argument.
19th Feb 2017, 1:00 AM
Sebastian Grigor
Sebastian Grigor - avatar