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

Tim Chase python.list at tim.thechases.com
Thu May 14 01:39:03 CEST 2009


Adam Gaskins 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,

Like "__init" instead of "__init__"? :)

> 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'?

Use self.<attribute> when you want the resulting "ser" object to 
live beyond the __init__ call.  Easily seen in this example:

   class Foo:
     def __init__(self):
       self.abc = 42
       xyz = 3.141
       # xyz now falls out of scope

     def test_me(self):
       print self.abc  # succeeds and prints 42
       print xyz       # fails because "xyz" doesn't exist
                       # within this scope

   f = Foo()
   print dir(f)  # has an "abc" but not an "xyz"
   f.test_me()

So in your case, unless you *need* to keep the comport/baudrate 
around, I'd just use
-tim

  DEFAULT_BAUD = 9600
  class Foo:
    def __init__(self, comport):
      self.comport = comport
      try:
        self.ser = Serial()
        self.ser.baudrate = DEFAULT_BAUD
        self.ser.open()
      except SomeSpecificException:
        print "Fail!"

so that the .ser object is available in other method-calls.

-tkc








More information about the Python-list mailing list