Newbie: ( if good in self: print "Foobar" )

Alex Martelli aleax at aleax.it
Mon Apr 28 09:08:43 CEST 2003


<posted & mailed>

David Broadwell wrote:
   ...
> class foo:
>     bar = ['B','A','R']
> 
>     def baz():
>         for item in bar: print item
>         boggle()
>         for item in bar: print item

This baz function just won't work -- its unqualified references to 'bar'
and 'boggle' can't be solved, and the "signature" (pattern of arguments,
namely none) is only compatible with a staticmethod or a free function,
not with an ordinary method as this appears to be.

>     def boggle(self):
>         self.bar[1] = 'a'
>         self.bar[2] = 'r'

This one, on the other hand, is fine.


> Question 1: Do I read it right that; a classes method called with self can
> change the 'global' value without having to type the bloddy global for
> every one?!? (ie: the above code not the below code)

No, it's NOT a *global* attribute -- it's an attribute of the CLASS.  You
can access an attribute of a class through any instance of that class, as
long as the instance hasn't "overridden" the attribute (i.e., bound an
attribute of the same name as a per-instance attribute on itself).

> Question 2: If that is true, what do we call this notation? (anyone got
> links?)

"Class attribute" is the normal way to call a class attribute.  In C++
or Java, those attributes are normally known as "static attributes".

>>>> bar = ['B','A','R']
>>>> def baz():
>         for item in bar: print item
>         boggle()
>         for item in bar: print item

Now this is quite fine.

>>>> def boggle(self):
>         self.bar[1] = 'a'
>         self.bar[2] = 'r'

However, this function needs an argument.  You're not passing that
argument when you call it, thus, boom.


>>>> baz()
> B
> A
> R
> Traceback (most recent call last):
>   File "<pyshell#4>", line 1, in ?
>     baz()
>   File "<pyshell#2>", line 3, in baz
>     boggle()
> TypeError: boggle() takes exactly 1 argument (0 given)
>>>>

Exactly: it needs exactly 1 argument and you didn't give it.


> Question 3: So what exactly does my code have to look like to work?
> Question 4: Is this notation only valid inside a class?

You can use the "notation" wherever you want, but you cannot call a
free function without arguments if it wants an argument.

To make the above-exemplified free-standing boogle function work,
you would have to pass it an object having an attribute named bar.
In this case, the object in question is the module in which the
functions baz and boggle live.  You can get at the module object
in the caller, though it's a rather fishy usage IMHO:

>>> def baz():
         for item in bar: print item
         import sys
         boggle(sys.modules[__name__])
         for item in bar: print item




Alex





More information about the Python-list mailing list