Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python variable scope

Tags:

python

scope

I'm teaching myself Python and I was translating some sample code into this

class Student(object):
    def __init__( self, name, a,b,c ):
        self.name = name
        self.a = a
        self.b = b
        self.c = c

    def average(self):
        return ( a+b+c ) / 3.0 

Which is pretty much my intended class definition.

Later in the main method I create an instance and call it a:

if __name__ == "__main__" :
    a = Student( "Oscar", 10, 10, 10 )

That's how I find out that the variable a declared in main is available to the method average and to make that method work, I have to type self.a + self.b + self.c instead.

What's the rationale for this?

like image 371
OscarRyz Avatar asked Apr 20 '10 18:04

OscarRyz


People also ask

What is scope of variable in Python?

A variable is only available from inside the region it is created. This is called scope.

What are the types scope of variable in Python?

You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.

How do I change the scope of a variable in Python?

Python global keyword is used to change the scope of variables. By default variables inside the function has local scope. Means you can't use it outside the function. Simple use global keyword to read and write a global variable inside a function.


1 Answers

Barenames (like a, b, c) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated -- e.g, if in your self.a = a the barename a could be scoped to mean what you appear to want (equivalent to self.a) then the assignment itself would be meaningless (assigning a name to itself), so you'd need further complicated rules.

Just using qualified names (like self.a) when you want something different than barenames' simple, straightforward, and optimized behavior, is by far the simplest approach -- perfectly workable, no complicated rules whatsoever, and allows the compiler to optimize things effectively (since e.g. a barename's scope is always lexically determined, not dependent on dynamically varying characteristics of the environment). So, besides perhaps nostalgia for other language with more complicated scoping rules, there's really no rationale for complicating the semantics of barenames.

like image 83
Alex Martelli Avatar answered Sep 25 '22 14:09

Alex Martelli