0
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?
2 Respostas
+ 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
+ 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 a.xyz="egg" the setter function will be called with the "egg" argument.