Private class and instance methods?

Daniel Klein danielk at aracnet.com
Mon Mar 12 15:52:24 CET 2001


I'm trying to get a grasp of the Python paradigm. Could you expound a bit on
the advantages of this over the seemingly simpler getX/setX methodology?

Seeing as there is virtually nothing that is really 'hidden' in Python (which
is a _good_ thing imo), why not simply use the _underscore rules (and good
documentation) to specify privacy?

Thanks,
Daniel Klein

On Sat, 10 Mar 2001 16:04:14 -0500, Mark Pilgrim <f8dy at diveintopython.org>
wrote:
>There is a better way to do this in Python, using the __getattr__ and
>__setattr__ special methods.
>
>class foo:
>    privatekeys = ('x',)
>    
>    def __init__(self, x):
>        self.x = x
>    def __getattr__(self, key):
>        print "getting private value %s" % key
>        return self.__dict__['__%s' % key]
>    def __setattr__(self, key, value):
>        if key in self.__class__.privatekeys:
>            print "setting private value %(key)s to %(value)s" % locals()
>            self.__dict__['__%s' % key] = value
>        else:
>            self.__dict__[key] = value
>
>if __name__=='__main__':
>    f = foo('abc')
>    print "f.x = %s" % f.x
>    f.y = []
>    print "f.y = %s" % f.y
>    f.x = 10
>    print "f.x = %s" % f.x




More information about the Python-list mailing list