What is the advantage of using get function for python class?

For example, in the code below, what is the advantage of the getName function?

class Node(object): def __init__(self, name): self.name = str(name) def getName(self): return self.name def __str__(self): return self.name 
+6
source share
4 answers

There is no use. People coming to Python from other languages ​​(like Java) sometimes do this because they are used to it. In Python, it makes no sense to create types of getters and setters that do nothing, but directly get and set the base variable. Properties allow you to transparently change the logic, if later you need to do something more complicated than just getting / setting a value.

It may be useful to use getters / setters, but in Python there is no real reason to use trivial getters / setters instead of just getting / setting the attribute directly. The only reason I can think of is if you have to maintain compatibility with an existing API that requires a specific set of methods.

+17
source

Do not use getter, just access the class attribute directly. Typically, recipients are used to access private / protected attributes, but in python there is no such thing. Another reason for using a getter is that you can do some work before returning the value, in your case it is not, but it may change in the future, do not worry when this time begins with the use of property decorator

 @property def name(self): return self._name 

you still get access to it, myObject.name , as well as direct access to it.

+3
source

I would expect production code to use @property . But since you asked, I’ll throw something away.

Perhaps the programmer would subclass Node and think it would be easier (or at least more explicit) to override getName to do special work. Just a thought!

But overall, as others have said, this is not what you usually see.

+2
source

Not. They are not needed in Python and are widely recommended against.

0
source

All Articles