class variable declarations...

Peter Hansen peter at engcorp.com
Mon Jun 16 18:00:44 CEST 2003


Lee John Moore wrote:
> 
> One may as well begin with Peter Hansen's letter to comp.lang.python:
> [..]
> >>
> >> class SpeedTouchComm:
> >>         "Interface with the SpeedTouch router"
> >>         def __init__(self, connect, uid, pwd, rtuid, rtpwd):
> >>                 self.connect = connect
> >>                 self.uid = uid
> >>                 self.pwd = pwd
> >>                 self.rtuid = rtuid
> >>                 self.rtpwd = rtpwd
> [..]
> 
> I've left the example in for reference.  :-)
> 
> > Not sure what you mean here.  "Class attributes" would
> > normally mean attributes that are shared by all instances of a
> > class, as if you were to do "SpeedTouchComm.rtuid = rtuid" in
> > the above, instead of using "self" which refers to an
> > *instance*, not the class.
> 
> I know.  I'm referring to connect, uid, pwd, etc. as attributes
> of the SpeedTouchComm class.  I referred to them as variables in
> a previous post (simply because I would refer to them as
> declared variables in a similar OP or C++ class), but I was told
> I should be calling them attributes.  So that's where that came
> from. :-)

Hmm... they're *not* class attributes though.  Or at least, not
how I use the term.  They are instance attributes, or merely
unadorned "attributes".  Calling them class attributes confuses
them with, for example, the capitalized constant I've added in
the following example:

class SpeedTouchComm:
    "Interface with the SpeedTouch router"

    DEFAULT_PORT = 577

    def __init__(self, connect, uid, pwd, rtuid, rtpwd):
        self.connect = connect
        self.uid = uid
        self.pwd = pwd
        self.rtuid = rtuid
        self.rtpwd = rtpwd


If some code wanted to refer to this constant, it could access it
as simply "self.DEFAULT_PORT" or, if it needed to change it (often
a bad idea, for a constant!) it would have to do this:

   SpeedTouchComm.DEFAULT_PORT = 566

or, sometimes better, sometimes worse:

   self.__class__.DEFAULT_PORT = 566

*All* instances that are created automatically have access to this
shared value because it is a *class* attribute, rather than an 
instance attribute.  All the items prefixed with self. are instance
attributes, and pertain only to a single instance of a class, 
never to all instances.

(The self.__class__ example above might be confusing but I left
it in as it does have times where it is a "better" way to write
the previous line.)

-Peter




More information about the Python-list mailing list