Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to set object instance variables

Tags:

python

oop

pylons

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.

like image 325
ensnare Avatar asked Mar 26 '10 07:03

ensnare


People also ask

What should instance variables be declared as?

Instance variables can be accessed in any method of the class except the static method. Instance variables can be declared as final but not static. The instance Variable can be used only by creating objects only. Every object of the class has its own copy of Instance variables.

How do you create an instance variable of an object?

Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

Where should instance variables be declared?

Instance Initializer Block in Java: An instance variable is a variable that is specific to a certain object. It is declared within the curly braces of the class but outside of any method. The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class.

Can objects be instance variables?

An object that is created using a class is said to be an instance of that class. We will sometimes say that the object belongs to the class. The variables that the object contains are called instance variables.


1 Answers

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.

like image 137
bcherry Avatar answered Oct 06 '22 01:10

bcherry