inicio mail me! sindicaci;ón

buildAccessor.py

You know there is something called properties in Python, don’t you??

I didn’t, and I’m used to other languages where one makes their own accessors for the properties (get and set methods, essentially).

I thought coding accessors was a very boring process, so I developed a little function to avoid it.

I gave it a SVN space, but you can just copy and paste the stable version:

from string import upper

def buildAccessor(list):
        #Variable declarations for the constructor
        for variable in list:
                print(\t\tself.__%s = %s’ % variable)
        print()

        #getXXX accessors
        for variable in list:
                identifier=variable[0]
                print(\tdef get%s(self):’ % (upper(identifier[0])+identifier[1:]))
                print(\t\treturn self.__%s’ % (identifier))
        print()

        #setXXX accessors
        for variable in list:
                identifier=variable[0]
                print(\tdef set%s(self, value):’ % (upper(identifier[0])+identifier[1:]))
                print(\t\tself.__%s=value’ % (identifier))
       
if __name__==‘__main__’:
        buildAccessor([
                (‘optionCapitalize’,‘True’),
                (‘configfile’,\’/etc/foo.conf\’),
                ])

And I wrote a little test:

class objectFoo:
        def __init__(self):
#1. Paste the results from buildAccessor from here:
                self.__optionCapitalize = True
                self.__configfile = ‘/etc/foo.conf’

        def getOptionCapitalize(self):
                return self.__optionCapitalize
        def getConfigfile(self):
                return self.__configfile

        def setOptionCapitalize(self, value):
                self.__optionCapitalize=value
        def setConfigfile(self, value):
                self.__configfile=value
#until here.
#2. Change what you need here:
if __name__==‘__main__’:
        test=objectFoo()
        print(‘test.getConfigfile() says \’ + test.getConfigfile() + \’)
        test.setConfigfile(‘/home/linz/.foo’)
        print(‘Now, test.getConfigfile() says \’ + test.getConfigfile() + \’)
#3. Then run it and good luck!

Maybe, next time I write another function to generate this tests.

Leave a Comment