[Tutor] Get/Set/Attribute Accessors in Python?
Francois Dion
francois.dion at gmail.com
Wed Dec 5 17:30:47 CET 2012
On Wed, Dec 5, 2012 at 10:38 AM, Malcolm Newsome
<malcolm.newsome at gmail.com> wrote:
> Hey Tutors,
>
> Python is/was my first language. Yet, I've recently begun learning C# for
> my new job.
My condolences.
> One thing I've come across in C# (and, quite frankly, am having a difficult
> time grasping) is Get and Set (Accessors).
> Since, I don't ever recall reading about this in Python, I'm wondering if
> they exist. If not, what is the "thinking" behind why they are not included
> in the language?
Nothing prevents you from creating getter and setter methods for all
your values in your class in Python, but really, you don't need to
most of the time. Refactoring and re-engineering your code later on to
use them if you have to, is pretty much transparent to the rest of the
code.
For example:
class Thing:
colorinfo = "#f00:red"
box = Thing()
print(box.colorinfo)
This will print:
#f00:red
You are happy about how short the code is and start using
box.colorinfo all over the place.
later, you decide, you should have used colorinfo as a method (a
getter, ie getcolorinfo() ) instead of a property, because you want to
add arguments to the constructor and use them in the getter. So you
would then have to go and replace every box.colorinfo by
box.colorinfo(), if you were not using python. But since you are, you
end up doing a getter, and keep the property:
class Thing:
def __init__(self,color,name):
self.color = color
self.name = name
def getcolorinfo(self):
return self.color + ':' + self.name
colorinfo = property(getcolorinfo)
box = Thing("#f00","red")
print(box.colorinfo)
box = Thing("#00f","blue")
print(box.colorinfo)
The output of which is
#f00:red
#00f:blue
The key here is that you are now wrapping the string inside a getter
function, where you could do all kinds of other stuff, but yet, you
never had to modify the print line since it still refers to a property
of the box instance of the Thing object. All because of the property
keyword.
Best of both worlds.
Francois
--
www.pyptug.org - raspberry-python.blogspot.com
More information about the Tutor
mailing list