It would be very nature if you want to encapsulate the getter and setter logic to the properties of your class. And it’s very easy via python 3 thanks to the new decorators. Let’s see how it works.
We wanna something like this:
It is easy if you just declare a class like below:
But let’s say you want to modify the getter logic to every time when the user retrieve the
myname property, you want to add a suffix of
is awesome. It should ring you a bell to the getter and setter in java, c# or other traditional OOP languages. You can achieve that for python 3 as well.
It is a simple python class which initialize a private property, pay attention that I use
self._myname rather than
self.myname, via this way, you are indicating this property is for internal use, below is a quote from PEP8:
_single_leading_underscore : weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore.
Notice that this is just a naming convention, people can still access this property to modify it.
Now let’s say that you want to use
myname as the public property name to expose. Then you just need to use the new
Let’s add this new method to your
Pay attention to the name of the method, it is the name of the public property. Now if you initialize an instance for the class, you will see that it works like a charm.
You will say it is just a plain method which happens to have the same name, but if you try to invoke the method, you will get an error:
Interesting, right? But it solves our getter thing aside, let’s tackle the setter.
The setter is easy as well:
Now you can re-assign the value for the property:
The whole code block is below: