Elegant python and elegant python

Source: Internet
Author: User

Elegant python and elegant python

For example, the following code

s = 'foo'd = {'a':1}def f():    s = 'bar'    d['b'] = 2f()print sprint d

Why do we need to declare the value of dictionary d without the global keyword?

This is because,

  • In the sentence s = 'bar', it is"Ambiguous"Because it can both represent referencing the global variable s or creating a new local variable, in python, the default action is to create a local variable, unless you explicitly declare global.
  • In the sentence d ['B'] = 2, it is"Clear"If we regard d as a local variable, it will report KeyError, so it can only reference global d, so we do not need to explicitly declare global.

The above two assignment statements are actually different actions. One isRebinding, One isMutation.


However

d = {'a':1}def f():    d = {}    d['b'] = 2f()print d

In the sentence d = {}, it is "ambiguous", so it creates a local variable d instead of referencing the global variable d, therefore, d ['B'] = 2 is also the local variable of the operation.


The essence of all these phenomena is"Is it clear".

If you think about it, you will find that not only dict does not need global, but all "Explicit" things do not need global. There is only one modification method for int-type 'str', that is, 'x' = Y'. This modification method is also the method for creating variables, which leads to ambiguity, I don't know whether to modify or create it. Dict/list/object can be used through dict ['X'] = y or list. modifications such as append () do not conflict with the creation variable, and do not produce ambiguity, so no explicit global is required.

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.