0
Can someone explain me the use of getters? I don't get it (ba dum tsss)
but seriously... i am taking the python course and im kinda stuck with OOP, in one lesson, there is a brief explanation of "getter" but as i just said, i dont get it and i really want to understand all the concepts (A clear example wouldn't be bad)
2 Antworten
+ 2
Python is not the best language to explain this concept. In other languages, there is a strict distinction between public and private variables and methods. Usually, class variables are private which means that they cannot be accessed from outside the class. Imagine a class Person with a variable age. If age was a public variable, you could create a Person object p and change its age like this: p.age = -42. -42 is a bad value for the age variable, you want to make sure that only reasonable values can be used. So you set the variable to private and declare a public setter method setAge(age) that checks the argument and will only change the value of the age variable if it is in a reasonable range of maybe 0-120. A public getter method is needed to access the private age variable from outside the class. And, as Toni Isotalo said, it allows you to execute other code while you're at it, instead of simply returning the variable's value.
+ 3
getters executes a function when you try to access a value of a property.
class a:
@property
def get(self):
#Do what ever you want
return "getter"
print(a().get);
Setters basically has the same idea.
Javascript has a lot of setters and would be better to explain.