[Tutor] scope, visibility?

Evert Rol evert.rol at gmail.com
Mon Nov 1 19:15:49 CET 2010


> Here is my main class:
> 
> class PenduGTK:
> 
> Inside the class is a method with a bit of code:
> 
>     def masque(chaine,liInd=0):
> 
>         i = 0
>         lenght = len(chaine)
> 
> The offending line is the one with len(chaine)
> 
> Here are the error messages:
> 
>  penduGTK.py 
> Traceback (most recent call last):
>   File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback
>     self.lblMot.set_text(self.masque(self.motChoisi))
>   File "/home/xxx/bin/penduGTK.py", line 44, in masque
>     lenght = len(chaine)
> AttributeError: PenduGTK instance has no attribute '__len__'

A method takes as its first argument a reference to the class. That is, in 'def some_method(blah1, blah2, blah3)', blah1 would be a reference to the class in which some_method is defined.
If you look at the error message, you see Python complains that the PenduGTK instance has no __len__ attribute, meaning 'chaine' is a PenduGTK instance: it's the first argument in the method, taking a reference to the class.
See eg http://diveintopython.org/object_oriented_framework/defining_classes.html
(also, carefully read the error and think what it could mean: it has a lot of hints to solve your problem).

Thus, define a method with an extra (first) argument. This is usually called self:

    def masque(self, chaine, liInd=0):


Last note on a totally different thing, because this confused me a bit: preferably avoid avoid the lowercase L, lowercase i and uppercase I next to each other. It's very hard to read. See eg http://www.python.org/dev/peps/pep-0008/ (section 'Names to Avoid'). To me, it initially read something like iiind=0. Which is ok, as long as I don't have to work with the code. But it may also bite you some day.


> I would think it has to do with namespaces, scopes and visibility. But how do I refer to built-in functions from inside a class?

Just as you did above: len(chaine). 
But since that wasn't your problem, I guess this answer is rather meaningless.

Cheers,

  Evert



More information about the Tutor mailing list