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

CM cmpython at gmail.com
Thu May 14 06:03:47 CEST 2009


On May 13, 6:36 pm, "Adam Gaskins" <agaskins... at kelleramerica.com>
wrote:
> 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

Others have said something like "use self prepended to an object if
you are
going to use it again".  I'd prefer to think of it more like "use self
prepended to an object if you'd like other functions to be able to
know
about that object.".  Is say this because you can have functions
called
over and over, and their contents "used again", but you still might
not
mind if their objects are local only to that function.

I just think of it that if I am going to need this object to be
generally
available to the whole class, I throw a self. on.  If not, I might not
bother.




More information about the Python-list mailing list