When *don't* I use 'self' in classes?

Adam Gaskins agaskins_ng at kelleramerica.com
Wed May 13 18:36:07 EDT 2009


I am a bit confused as too when, if ever, it is not appropriate to prepend 
'self' to objects in a class. All of the examples of how to use 'self' that 
I find seem to be short and very simple (as examples tent to be). I 
appologize if I am asking an ignorant question here, but I want to get off 
on the right foot. Here's an example of what I mean:

import serial
class foo:
    def __init(self, comport):
        self.comport = comport
        self.baudrate = 9600 #default
        self.ser = serial
        try:
            self.ser.Serial()
            self.ser.baudrate = self.baudrate
            self.ser.open()
        except:
            print 'Serial port could not be opened'

=== OR ===
import serial
class foo:
    def __init(self, comport):
        self.comport = comport
        self.baudrate = 9600 #default
        try:
            ser = serial.Serial()
            ser.baudrate = self.baudrate
            ser.open()
        except:
            print 'Serial port could not be opened'

There may be a typo in here, this is just a random example similar to 
something I'm working with, but which one of these are more 'proper'? If I 
am importing a library do I still prepend it's object with self when I use 
it in my class? I suppose my question is just basically... when do you NOT 
prepent an object in a class with 'self'?

I'm not even sure I'm using the term 'object' correctly here. Feel free to 
set me straight, but I hope my example makes it clear what I am asking.

Thanks a lot, this ng has already been super helpful as I take my 
crash-course in to python! :P 





More information about the Python-list mailing list