Python's locals () function

Source: Internet
Author: User

The Python locals () function returns all local variables of the current position in the Dict type.

Example code:

deffunc (): Arg_a, Arg_b='a','b'    deffunc_a ():Pass    deffunc_b ():Pass    defprint_value ():Print(Arg_a, Arg_b)returnlocals ()if __name__=='__main__': Args=func ()Print(Type (args))Print(args)

As you can see from the running result, the local variable of the function func is returned as the dict type.

<class 'Dict'>{'func_a': <function func.<locals>.func_a at 0x10d8f71e0>'Arg_b':'b','arg_a':'a','Print_value': <function func.<locals>.print_value at 0x10d8f7378>'Func_b': <function func.<locals>.func_b at 0x10d8f72f0>}

Combine locals () with property to improve code readability

classNewprops (object):def __init__(self): Self._age= 40defFage (): Doc="The Age property ."        defFset (self, value): Self._age=int (value)defFget (self):returnSelf._agedefFdel (self):delSelf._agereturnlocals () age= Property (* *Fage ())if __name__=='__main__': x=newprops ()Print(x.age) x.age= 50Print(X.age)

It is important to note that the Fage () method under the 4 property names cannot be modified (nor can new properties be added, unless the locals () returned dict is processed to remove the extra elements), must be Fset, Fget, Fdel, Doc, if the property name is modified, the following exception is thrown:

' F_set '  is  for this function

Because the property method receives 4 parameters (except for self, because the Python compiler automatically passes in)

def __init__ # known special case of property.__init__
.....

At return locals (), the value of the returned Dict,key corresponds to the parameter's name one by one, passing in the Function property in the form of a **kwargs parameter.

Python's locals () function

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.