Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit to using a 'get function' for a python class? [closed]

For example, in the code below, what is the benefit 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
like image 455
Chris Avatar asked Dec 13 '12 03:12

Chris


People also ask

What is the benefit of class method in Python?

It makes it clearer that the method doesn't use any state from the instance, usually named self . Also it means you can test it on the class without creating an instance. Also, if this class doesn't contain much else, it's probably better to use a function and functools.

What is the purpose of using classes Python?

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.

How do you call a function inside a class in Python?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.


1 Answers

There is no benefit. People coming to Python from other languages (e.g., Java) sometimes do this because they're used to it. In Python there is no point to creating these sorts of getters and setters that don't do anything but directly get and set the underlying variable. Properties allow you to transparently swap in logic if at a later time you need to do something more complex than just get/set the value.

There can be a benefit in using 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 would be if you have to maintain compatibility with an existing API that requires a certain set of methods to be available.

like image 86
BrenBarn Avatar answered Sep 21 '22 13:09

BrenBarn