Proper way to set object instance variables

ensnare picture ensnare · Mar 26, 2010 · Viewed 31.8k times · Source

I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean:

class User(object):

    def setName(self,name):

        #Do sanity checks on name
        self._name = name

    def setPassword(self,password):

        #Check password length > 6 characters
        #Encrypt to md5
        self._password = password

    def commit(self):

        #Commit to database

>>u = User()
>>u.setName('Jason Martinez')
>>u.setPassword('linebreak')
>>u.commit()

Is this the right approach? Should I declare class variables up top? Should I use a _ in front of all the class variables to make them private?

Thanks for helping out.

Answer

bcherry picture bcherry · Mar 26, 2010

It's generally correct, AFAIK, but you could clean it up with properties.

class User(object):

    def _setName(self, name=None):
        self._name = name

    def _getName(self):
        return self._name

    def _setPassword(self, password):
        self._password = password

    def _getPassword(self):
        return self._password

    def commit(self):
        pass

    name = property(_getName, _setName)
    password = property(_getPassword, _setPassword)

>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()

There's a also a convenient decorator-based syntax, the docs explain that too.