[Tutor] class methods: using class vars as args?

Alan Gauld alan.gauld at btinternet.com
Sun May 23 21:54:04 CEST 2010


"Alex Hall" <mehgcap at gmail.com> wrote

> class c(object):
> def __init__(self, arg1, arg2):
>  self.arg1=arg1
>  self.arg2=arg2
>
> def doSomething(self, arg3=self.arg1):
>  ...
>
> The above results in an error that "name 'self' is not defined". Why
> can I not set the default values of a method's arguments to class 
> vars
> like that? Thanks!

Because they are not class vars they are instance vars.
self.arg1 does not exist until after an instance has been
created and they have been set by __init__. At the time
the class is defined self.arg1 does not exist.

You could do

class c(object):
 defArg = 42
 def __init__(self, arg1, arg2):
    self.arg1=arg1

 def doSomething(self, arg3=defArg):
  ...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk




More information about the Tutor mailing list