1

So I'm in school for computer science and we are learning about classes(in python more specifically). I would say that I'm an intermediate level programmer and I've worked with classes before but now they are telling me to do something I've never done

Usually, when I work with classes and I want to get a value I just call the value by name i.e.foo.val but now I'm being told that this is bad practice and I should be writing getter methods.

class ClassName:
    def __init__(self, val1, val2):
        self._val1 = val1
        self._val2 = val2

    def getVal1(self):
        return self._val1

    def getAccountNumber(self):
        return self._val2

What I really would like to know is what is the benefit of using a getter method as opposed to just getting the variable by name

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
MasterMs
  • 11
  • 2
  • 1
    They are in many cases nearly pointless and a remnant of other languages where they have a more legitimate use. Such as the preferred language of whomever is telling you to blindly use getters/setters in Python. – Brad Solomon Oct 03 '19 at 22:33
  • getter methods like this are not idiomatic in Python, but in other languages, they are for maintaining *encapsulation*, a fundamental OOP concept. In Python, we can use alternative approaches that avoid the boilerplate of getters/setters but still maintain encapsulation: descriptors (e.g. `property`) – juanpa.arrivillaga Oct 03 '19 at 22:33
  • Also see https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters – R. Arctor Oct 03 '19 at 22:33
  • If the value is calculated you can't just access the attribute. Getters hide the implementation. Python uses properties rather than `get/set` functions. Other than for basic data types, I try to orient my objects so there are no getters or setters. Just tell the object what to do and let it do it. – Peter Wood Oct 03 '19 at 22:34
  • So, a lot of curriculums are still just teaching "Java in Python", but in any case, the fundamental idea is important: https://en.wikipedia.org/wiki/Information_hiding – juanpa.arrivillaga Oct 03 '19 at 22:37
  • 1
    @PeterWood yes, there is definitely an argument for "getters/setters are an antipattern". – juanpa.arrivillaga Oct 03 '19 at 22:37

0 Answers0