The namespace in Python

Source: Internet
Author: User

Namespaces in Python are mappings of names (identifiers) to objects.

Specifically, Python holds a dictionary (__dict__) for modules, functions, classes, and objects, which is a mapping of rename-to-object.

You can see the output of the Python program below:

Print (' globals: ') print (Globals (). keys ()) print (") x = 1print (' globals after definition of x: ') print (Globals (). Keys ()) Print (") if x = = 1:    y = 2    z = 3    print (' Globals inside if:%s '% (Globals (). Keys ()))    print (' Locals inside I F:%s '% (locals (). Keys ())    del y    print (' Locals after del:%s '% (locals (). Keys ()))

In object-oriented programming, one of the biggest differences between Python and C + + is that namespace in Python can be dynamically changed, members of classes, members of class instances can be added dynamically, but simply add an item to the corresponding namespace dictionary. The values specifically noted here, functions (member functions or global functions) also have their own namespace dictionaries and can even be dynamically added

Class Test1 (object):    x = 1    def __init__ (self):        self.y =  2        self.z = 3    def func (self):        print (' Test ')    func.fx = 2print (test1.__dict__) t1 = Test1 () print (t1.__dict__) print (t1.func.__dict__)

As a result, we can understand what the so-called constructor __init__ in Python did, because the first member method passed in is a self reference, which is equivalent to

T1 = Test1 () calls test1.__init__ (T1) and then adds a T1 dictionary entry for class instance namespace in the constructor

The namespace in Python

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.