Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use locals and globals in Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you about how to use locals and globals in Python. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

1. Local namespace-specifically refers to the method of the current function or class. If the function defines a local variable, xcentine, Python uses the

This variable, and then stop searching.

two。 Global namespace-specifically refers to the current module. If the module defines a variable, function, or class named x, Python

This variable is used and the search is stopped.

3. Built-in namespace-global for each module. As a last resort, Python will assume that x is a built-in function or variable.

If Python cannot find x in these namespaces, it will abandon the lookup and throw an exception for NameError, passing in

A message like There is no variable named'x'.

# Local variable function locals example (locals returns a dictionary of name / value pairs. ):

[python] view plain copy print?

Def foo (arg, a):

X = 1

Y = 'xxxxxx'

For i in range (10):

J = 1

K = I

Print locals ()

# print result of calling function

Foo (1 dint 2)

# {'asides: 2,' iTunes: 9, 'KTH: 9,' jacks: 1, 'arg': 1,' yearly: 'xxxxxx',' x rays: 1}

The difference between from module import and import module. Using import module, the module itself is imported

But it maintains its own namespace, which is why you need to use the module name to access its functions or properties (module.function)

The reason. But with from module import, you actually import the specified functions and properties into your own name from another module.

Space, which is why you can access them directly without referring to the module from which they come from.

This is how locals and globals are used in Python shared by Xiaobian. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report