global name 'self' is not defined - noob trying to learn

mark.seagoe at gmail.com mark.seagoe at gmail.com
Mon Mar 30 07:18:26 CEST 2009


On Mar 29, 9:52 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Sun, Mar 29, 2009 at 9:18 PM,  <mark.sea... at gmail.com> wrote:
> > Hi.  So now I have this class that works to allow me to pass in my
> > reg_info struct.  However when I try to make it part of my class it
> > gets an error "global name 'self' is not defined.  I've never seen
> > this error before.  If I comment out the line below 'self.reg_info =
> > reg_info" then the code runs... but I need to add stuff to this class,
> > and so I'm wondering why I can't use 'self' anymore?
>
> `self` is not magical or a language keyword. It's just the
> conventional name for the first argument to an instance method (which
> is the instance the method is acting upon). For example, a small
> minority use `s` instead for brevity. There is no variable `self` in
> the parameters of __new__(), hence you get a NameError, as you would
> when trying to access any other nonexistent variable.
>
> Also, you shouldn't use `class_ ` as the name of the first argument to
> __new__(). Use `cls` instead since that's the conventional name for
> it.
>
> My best guess as to what you're trying to do is (completely untested):
> class myclass(long):
>     def __new__(cls, init_val, reg_info):
>         print reg_info.message
>         instance = long.__new__(cls, init_val)
>         instance.reg_info = reg_info
>         return instance
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Thanks Chris.  It was tested working (with the offending line editted
out).
Yep this is helpful - I thought 'self' was a keyword.  And I see I
should differentiate the instance methods and objects from the cls
reference.



More information about the Python-list mailing list