[Tutor] Some help with properties and accessor functions....

Alan Gauld alan.gauld at freenet.co.uk
Wed Apr 19 19:34:29 CEST 2006


class SOFileIndexRecord(object):
    def __init__(self, so):
        self._so=so

    def _get_code(self):
        return self._so.code
    def _set_code(self, value):
        self._so.code=value
    testCode=property(_get_code, _set_code) # What does this do?

It says that testCode is a property of SOFileIndexRecord
A property looks like a data attribute from the user of the 
class's point of view but internallty it is accessed via the 
get/set methods.

Thus I can do:

s = SOFileIndexRecord(mySo):
s.testCode = myCode   # actually does s._setCode(myCode)
print s.testCode            # actually s._getCode()

properties allow for creation of read only attributes in Python 
by having a null set method.(Of course you can still cheat and 
use the 'hidden' methods, or even the real data attributes. Buit 
if everyone behaves properly it can help a wee bit.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list