Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [python-tip] Properties
Index -> Programming, Python -> Python Tutorials
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Python -> Python Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: