
-----------------------------------
wtd
Mon Sep 29, 2008 12:56 am

[python-tip] Properties
-----------------------------------
Frequently I see code like the following.

class Foo(object):
    def __init__(self, bar):
        self.bar = bar
    def get_bar(self):
        return self.bar
    def set_bar(self, bar):
        self.bar = bar

f = Foo(42)
print f.get_bar()
f.set_bar(37)
print f.get_bar()

Now, obviously we don't need get_bar in this case because the bar field is public.  The set_bar function is not strictly necessary either.

But, making attributes of an object private is a good idea, so...

class Foo(object):
    def __init__(self, bar):
        self.__bar = bar
    def get_bar(self):
        return self.__bar
    def set_bar(self, bar):
        self.__bar = bar

f = Foo(42)
print f.get_bar()
f.set_bar(37)
print f.get_bar() 

But now our code has to look all Java-like with explicit setters and getters.  Ugly.  

What if we could keep the attribute private but still use:

f = Foo(42)
print f.bar
f.bar = 37
print f.bar  

There is!

class Foo(object):
    def __init__(self, bar):
        self.__bar = bar
    def __get_bar(self):
        return self.__bar
    def __set_bar(self, bar):
        self.__bar = bar
    bar = property(__get_bar, __set_bar)

Use your new power responsibly.
