Computer Science Canada

[python-tip] Properties

Author:  wtd [ Mon Sep 29, 2008 12:56 am ]
Post subject:  [python-tip] Properties

Frequently I see code like the following.

code:
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...

code:
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:

code:
f = Foo(42)
print f.bar
f.bar = 37
print f.bar


There is!

code:
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.


: