Python本地与全局命名空间用法实例

yipeiwu_com6年前Python基础

本文实例讲述了Python本地与全局命名空间用法。分享给大家供大家参考。具体如下:

x = 1
def fun(a):
  b=3
  x=4
  def sub(c):
    d=b
    global x
    x = 7
    print ("Nested Function\n=================")
    print locals()
  sub(5)
  print ("\nFunction\n=================")
  print locals()
  print locals()["x"]
  print globals()["x"]
print ("\nGlobals\n=================")
print globals()
fun(2)
 
///scope.py
Globals
=================
{'x': 1,
 '__file__':
'C:\\books\\python\\CH1\\code\\scope.py',
 'fun': <function fun at 0x008D7570>,
 't': <class '__main__.t'>,
 'time': <module 'time' (built-in)>,. . .}
Nested Function
=================
{'c': 5, 'b': 3, 'd': 3}
Function
=================
{'a': 2, 'x': 4, 'b': 3, 'sub':
  <function sub at 0x008D75F0>}
4
7

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python绘图模块matplotlib示例详解

python绘图模块matplotlib示例详解

前言 Matplotlib 是 Python 的绘图库。作为程序员,经常需要进行绘图,在我自己的工作中,如果需要绘图,一般都是将数据导入到excel中,然后通过excel生成图表,这样操...

Django+JS 实现点击头像即可更改头像的方法示例

Django+JS 实现点击头像即可更改头像的方法示例

首先,在models.py中创建UserModels类 from django.db import models from django.contrib.auth.models im...

djano一对一、多对多、分页实例代码

昨日内容: ORM高级查询 -filter id=3 id__gt=3 id__lt=3 id__lte=3 id__gte=3 -in /not in .filter(id__i...

python3+PyQt5实现使用剪贴板做复制与粘帖示例

python3+PyQt5实现使用剪贴板做复制与粘帖示例

本文是对《Python Qt GUI快速编程》的第10章的例子剪贴板用Python3+PyQt5进行改写,分别对文本,图片和html文本的复制与粘帖,三种做法大同小异。 #!/usr...

Pytorch 多块GPU的使用详解

Pytorch 多块GPU的使用详解

注:本文针对单个服务器上多块GPU的使用,不是多服务器多GPU的使用。 在一些实验中,由于Batch_size的限制或者希望提高训练速度等原因,我们需要使用多块GPU。本文针对Pytor...