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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With