0

Hi, recently I read some codes of others , and found the differences between others and mine is that they often write a function to get class member. Like

def GetHeight
    return self.height

instead of just using

self.height

in the program.

I mean, in C++, I know the function of this is to get private member.
In python, though everything is set as public (in normal cases) ,
Why it has reason to be used in python? Is that just bad code? Or something else I ignore?
I am kinda new to python, so I will appreciate it if you give some advice.

EDIT:
Similar Question It seems my question has been identified as the duplicate of another one. I checked the answer and found the answer of that is more like general advice instead of pythonic programming.

While the answer below introduces a feature of python -- property
That possibly cannot be learned from that question, so it's the reason I think my question is unique.

DoubleX
  • 351
  • 3
  • 18

2 Answers2

2

In Python it is unnecessary to create a getter method (especially if the getter simply returns the attribute value with no checks or modifications). You can implement meaningful get and set methods but they should actually do something. The preferred approach is to use property decorators as described here: How does the @property decorator work?

class Building(object):
    def __init__(self):
        self._height = 100

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        if 0 < value < 1000:
            self._height = value
        else:
            raise ValueError('Attribute: height must be between 0 and 1000.')

Then the property methods are used when reading from or assigning to the attribute:

b = Building()

print(b.height)
100

b.height = 90
print(b.height)
90

b.height = 2000
print(b.height)
90

By convention, reserved attributes are preceded by a single underscore and private attributes by a double underscore. However, this is more to alert users of the class that the attributes should be handled with care and nothing prevents them from accessing the attributes.

Apollo2020
  • 509
  • 2
  • 8
  • Upvoted, but the setter should raise a `ValueError`, not just silently swallow the error. – Kevin Dec 07 '17 at 05:29
1

it's a matter of preference. python lets the programmer be OO or imperative as suits. the whole notion of accessors and mutators is old fashioned for some and beloved by others.

ShpielMeister
  • 1,417
  • 10
  • 23