Home In python,why use function to get class member?
Reply: 2

In python,why use function to get class member?

Shawn Xu
1#
Shawn Xu Published in 2017-12-07 05:00:45Z

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.

Apollo2020
2#
Apollo2020 Reply to 2017-12-07 05:46:08Z

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.

ShpielMeister
3#
ShpielMeister Reply to 2017-12-07 05:06:17Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300322 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO