[Tutor] Local variable look up outside the function and method

Alan Gauld alan.gauld at yahoo.co.uk
Sun May 12 09:45:56 EDT 2019


On 12/05/2019 14:04, Arup Rakshit wrote:

The first case x is a global variable - which in
Python really means module level.

In the second case you have placed it inside
Foo so you need to specify that that is where
it is located. Classes encapsulate their own
methods and attributes, that is one of their
purposes. and just as you can't access a method
without preceding it with self similarly you
can't access an attribute without providing
the object or class reference.


> I figured I have to access it like:
> 
> In [1]: class Foo:
>    ...:     x = 10
>    ...:     def bar(self):
>    ...:         return self.__class__.x

Remember that any time you find yourself using
dunder techniques ask if there is an easier way.
There usually is...

You can just use

                 return self.x

or, possibly better:

                 return Foo.x

You know x is declared in the context of Foo so refer
to it directly. The self approach runs the risk of an
instance attribute of the same name being created and
overriding the class attribute. (But sometimes that's
what you want.)

If you had an inheritance hierarchy where x was defined
in multiple places the .__class__ approach would work
better (probably even be needed). But in most cases these
kinds of variables are defined once in the class and
you are safe to access it by name - and it makes the
code more readable and unambiguous.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list