class variable declarations...

Peter Hansen peter at engcorp.com
Mon Jun 16 10:32:41 EDT 2003


Lee John Moore wrote:
> 
> Is using __init__() to force the setting of various class attributes really not
> frowned upon?  Or is there another way of doing this that's considered more
> acceptable?
> 
> 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
> 
> It just seems against the law to be creating instances of SpeedTouchComm and
> accessing class attributes that aren't even referred to outside the __init__()
> function.

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.

Also, what do you mean by "against the law"?  The above example seems
to be exactly how *all* Python code works, where you pass values in
to the __init__ method and it dutifully assigns them to various names
in self.  I don't think you're being clear, sorry.

Maybe the short answer will do: there's nothing wrong with the above.
It even exhibits good coding style! :-)

-Peter




More information about the Python-list mailing list