Scope of variables in Python (variable scope)

Source: Internet
Author: User
Tags variable scope

Scope of variables in Python (variable scope) This article aims

This article mainly discusses and summarizes the scope of variables in Python (variable scope).

The aim is to make a more thorough understanding of the scope of variables in Python through code, illustrations, and text descriptions;

To avoid, in the process of writing code, because the concept is not clear, resulting in the use of wrong variables, resulting in code errors and variable meaning error and so on.

If there is any mistake, please correct me.

Explains the scope of variables in Python python variable Scope interpretation code version

The sample code used is mainly from:

"Grooming" Python: the Meaning of self and init__ + why you have self and __init__

In the following:

?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 #!/usr/bin/python# -*- coding: utf-8 -*-"""-------------------------------------------------------------------------------Function:【整理】Python中:self和init__的含义 + 为何要有self和__init__http://www.crifan.com/summary_the_meaning_of_self_and___init___in_python_and_why_need_themAuthor:     CrifanVerison:    2012-11-27-------------------------------------------------------------------------------"""#注:此处全局的变量名,写成name,只是为了演示而用#实际上,好的编程风格,应该写成gName之类的名字,以表示该变量是Global的变量name = "whole global name"; class Person:    name = "class global name"    def __init__(self, newPersionName):        #self.name = newPersionName;                #此处,没有使用self.name        #而使得此处的name,实际上仍是局部变量name        #虽然此处赋值了,但是后面没有被利用到,属于被浪费了的局部变量name        name = newPersionName;    def sayYourName(self):        #此处,之所以没有像之前一样出现:        #AttributeError: Person instance has no attribute ‘name‘        #那是因为,虽然当前的实例self中,没有在__init__中初始化对应的name变量,实例self中没有对应的name变量        #但是由于实例所对应的类Person,有对应的name变量,所以也是可以正常执行代码的        #对应的,此处的self.name,实际上是Person.name        print ‘My name is %s‘%(self.name); # -> class global name        print ‘name within class Person is actually the global name: %s‘%(name); #-> whole global name        print "only access Person‘s name via Person.name=%s"%(Person.name); # -> class global namedef selfAndInitDemo():    persionInstance = Person("crifan");    persionInstance.sayYourName();    print "whole global name is %s"%(name); # -> whole global name    ###############################################################################if __name__=="__main__":    selfAndInitDemo();

Illustrated version of the interpretation of the Python variable scope

Here's a graph to explain:

Text version of the interpretation of the Python variable scope

A brief description of the text is:

Global variables (globals variable)

In any other common function or class, it can be directly referenced by the corresponding variable name.

Local variables (automatic variable)

For functions within a function, including classes class, normal variables are automatically temporary variables.

Background information is here:

Precedence Relationship of variables

The most important difference between the scope of ordinary local variables and global variables is:

Internal variables have precedence over external variables

Here, local variables (within functions), precedence greater than, (external) global variables

Other words:

A. If a variable with the same name as the global variable appears inside the function, it is a local variable;

B. If, within a function, there is no local variable with the same name, the corresponding variable is a global variable.

The precedence of this variable applies not only to the Python language, but also to almost all other languages, such as c/c++/c# and so on.

So, the name in __init__ in the above example is not a global variable:

Name = "Whole global name";

In the name instead of the local variable;

Where, in this case, it belongs to the type of Python (and, or other special) language that is unique and can be used directly without declaring variables.

That is, the local variable name, which is not declared, but is directly used, by:

name = Newpersionname;

In the initialization, set to the corresponding name, here is "Crifan".

Classes (Class) variables

class, within the scope of the class, only through the

ClassName.PropertyName

Or,

Classname.variablename

To access the current class classname variable propertyname

In the example, it is through

Person.name

To access the value of the variable name in the class person.

Variables for example (Instance)

The variables in the example, in theory, are

Instanceobject.propertyname

To visit.

And here, because of Python, the default, customary notation, the first parameter of the class function is defined as the name of the instance variable, and the name is self, so it becomes:

Self. PropertyName

The

So, in the function of the class above, if you want to access the variable of instance, it is through

Self.name, go to the variable name in the example self that accesses the class person.

Summarize

So, to thoroughly understand the scope of variables;

Or write a lot of code to test yourself.

and preferably with other different languages relevant background knowledge, in order to more convenient to achieve horizontal contrast, achieve mastery, extrapolate effect.

Scope of variables in Python (variable scope)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.