[Tutor] scope, visibility?

Steven D'Aprano steve at pearwood.info
Tue Nov 2 00:37:06 CET 2010


Samuel de Champlain wrote:

> Inside the class is a method with a bit of code:
> 
>     def masque(chaine,liInd=0):
>         i = 0
>         lenght = len(chaine)

As this is a method, you normally need to refer to the instance in the 
definition:

def masque(self, chaine, liInd=0):
     i = 0
     length = len(chaine)

There are exceptions to this -- class methods and static methods -- but 
you should consider them for advanced use. Normally, so long as you 
remember to put self as the first argument to the method, you will be right.

Because you left that out, Python assigned the instance to "chaine" and 
what you expected to be chaine to "liInd", leading to unexpected results.


> 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__'
> 
> 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?

Nothing to do with any of those things.



-- 
Steven



More information about the Tutor mailing list