Namespaces in functions vs classes

Ethan Furman ethan at stoneleaf.us
Sun Apr 17 16:41:53 EDT 2011


Gerald Britton wrote:
> For my
> final attempt, I add the prefix "a." to my use of "foo"
> 
>>>> class a():
> ...     foo = 'foo'
> ...     def g(x):
> ...         return a.foo
> ...


The first parameter to any method in a class* is going to be the 
instance of that class, and is usually named 'self'.  So your above code 
(to stick with your 'x') should be:

     def g(x):
         return x.foo

or to follow normal naming conventions:


     def g(self):
         return self.foo

~Ethan~

*It is also possible to write special methods that take the class as the 
first argument (classmethod) or don't take either (staticmethod).



More information about the Python-list mailing list