Elegant python-scope and lookup strategies

Source: Internet
Author: User

First understand what a namespace is, a namespace is a "named-and-object" mapping, implemented in Python with Dict.

The scope, however, refers to namespaces that can be accessed directly.


When we access a variable, we will follow the order of LEGB to lookup:

    • L->local. That is, local variables, such as variables defined in def or lambda.
    • E-> enclosing function locals. That is, the variable in the closure.
    • G->global (module). Global variables.
    • B->built-in. Built-in variables, such as Len ()/keyerror.


When we access an attribute through an instance, self.x, its lookup order is:

    • Instance Properties
    • Class properties
    • The parent class property. By MRO (method resolution Order)
Give a chestnut a more intuitive point. [Python]View Plaincopy
    1. s = ' global '
    2. Class Foo (object):
    3. s = ' class '
    4. def __init__ (self):
    5. print s #全局变量, output global
    6. print Foo.s #类属性, Output class
    7. print self.s #实例属性中没找到, so look in the class attribute, output class
    8. Self.s = ' instance '#创建了个实例属性
    9. print self.s #实例属性能找到, output instance
    10. Foo ()

Elegant python-scope and lookup strategies

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.