Python:变量的作用域与LEGB原则

Python--LEGB原则 一、 命名空间 先来一段概要总结: 白话一点讲:命名空间是对变量名的分组划分。 不同组的相同名称的变量视为两个独立的变量,因此隶属于不同分组(即命名空间)的变量名可以重复。 命名空间可以存在多个,使用命名空间,表示在该命名空间中查找当前名称。 虽然命名空间是一个跟具体语言无关的概念,但是,不同的语言由于机制不同,因此在表现上还是有差别的。例如下述Python的例子: x = 10 def foo(): global x x += 1 print x 在这个例子中,使用函数外部 阅读详情

函数是Python中的第一类对象 ,可以把函数赋值给变量,对该变量进行调用,可实现原函数的功能。
(变量——函数——函数式编程)

1. 作用域 / 命名空间

1.1 作用域的定义

作用域:程序创建、访问、改变一个变量时,都是在一个保存该变量的空间内进行,这个空间为命名空间,即作用域。
python作用域是静态的,变量被赋值、创建的位置决定了其被访问的范围,即变量作用域由其所在位置决定。

1.2 作用域的前提

Python中,作用域的概念仅仅存在于:当变量在Module(模块)、Class(类)、def(函数) 中定义的时候

理解这一点至关重要! 对于LEGB原则准确、快速的理解很有帮助。

再说的直白点,作用域存在于 def和 class之内的缩进代码块 .py后缀Python文件中!

2. LEGB 原则

Python 的变量名解析机制也称为 LEGB 法则:</

Python变量作用域与多py文件之间变量传递【实战笔记|Flask项目适用】 本文详解Python变量作用域(LEGB规则)及多文件间变量传递机制,结合Flask项目实战,指出全局变量仅限单文件有效,跨文件需通过import导入。推荐使用配置文件(如config.py)、函数返回值或类实例传递数据,避免循环导入与全局变量滥用。强调函数传参、模块化设计为最佳实践,助力蓝图开发高效稳定。 阅读详情

相关推荐

ICCompiler II学习笔记(一)ICC II使用全流程 overview

学习笔记同步发布在我的个人网站上,欢迎来访查看。 个人学识有限,理解可能有误,仅供参考。 文章目录一、前言二、 ICC II 简介和 GUI2.1 Blocks 和 Design Libraries2.2 Objects2.3 Application Options三、Design Setup四、APR flow五、 课程主题:如何用 ICC II来实现最好的PPA 一、前言 现在的芯片都在追求一个极致的PPA 芯片的生成可以分为以下 5大步骤: Front-end Design:前端设计,最终产生

一名FPGA芯片设计爱好者的技术博客 2万+

Klipper-源码模块

Klippy上位机程序采用多线程架构,包含四个主要进程:主线程处理G代码命令、串口IO线程(C语言实现)、MCU响应处理线程(Python实现)和独立日志线程。代码结构分为三大模块:chelper(C语言辅助函数)、extras(扩展功能如温度控制)和kinematics(运动学模型实现)。核心功能模块包括串口通信(serialhdl.py)、步进电机控制(stepper.py)、运动学计算等,其中C语言实现的底层模块通过serialqueue.c处理高效IO。扩展模块支持热床、传感器等外设,运动学子模块提

weixin_44258581的博客 991

案例分析|一篇文章带你看懂养鸡场智慧管理系统

养鸡场智慧管理系统是为了满足现代化养鸡业对精细化管理的需求而设计的一款专业软件。随着科技的发展和农业产业的升级,传统的手工记录和管理方式已无法满足高效、准确和实时的数据跟踪需求。本软件旨在通过集成各种功能模块,帮助养鸡场主实现从鸡苗孵化、饲养管理、饲料控制到销售结算等全链条的智能化操作。该系统的核心目标是提升养鸡场的运营效率和盈利能力,通过自动化数据处理,减少人工误差,节省时间和精力。例如,孵化报表和记录模块可以帮助管理者实时监控孵化过程,及时调整策略;

muyu2980的专栏 930

mfcc总结,这个mel三角滤波器分组到底是如何起作用的呢?

先看fft频谱图(这是4096字节取样fft计算,横轴频率是从0到512,后边意义不大,未取,纵轴是振幅),那些我随便画的蓝色线,你有什么联想?: 再看,这绿色线,是否有一种上升后,便逐渐式微的感觉,都是三角形的,这或许也是mel当初和绝大多数人看到的: 如果在振幅上加上一条限制的黑线(振幅门槛限制),黑色线以下很多频率就没有意义了,你看,有用的频率连一半(512/2=256)都占不到...

ganggangwawa的博客 9908

ST7789T3与CST816D驱动全解析,面试技巧第11篇:嵌入式面试场景问答 10 连发。

SPI模式下,SCLK、MOSI、CS、DC、RST为必需引脚;8080模式下需连接D0-D7、WR、RD等信号线。CST816D触摸芯片通常通过I2C接口通信,需连接SCL、SDA及INT(中断)引脚。确保电源引脚(VCC、GND)稳定供电,ST7789T3典型工作电压为3.3V。显示异常时检查时序参数,如SPI时钟频率(建议≤40MHz)、数据建立时间。初始化流程需发送一系列命令序列,包括设置像素格式、扫描方向、帧率控制等。扫描方向(MADCTL)可调整显示旋转角度,需根据实际硬件布局配置。

a967gsvj的博客 374

Python实战:3分钟搞定A股K线数据抓取(附东方财富/腾讯API完整代码)

本文为量化交易初学者提供了一份快速获取A股K线数据的实战指南。通过对比东方财富与腾讯财经两大免费API的优劣,并附上可直接运行的完整Python代码,帮助读者在3分钟内搭建起自己的数据抓取管道,为构建量化交易系统奠定坚实的数据基础。

weixin_29062255的博客 2909

coreldraw sp2精简版 x4_CorelDRAW X4下载-CorelDRAW X4 SP2 精简版_Win10镜像官网

CorelDRAW X4 SP2是一个专业图形设计软件,专用于矢量图形编辑与排版,借助其丰富的内容和专业图形设计、照片编辑和网站设计软件,您将能够随心所欲地表达自己的风格与创意,轻松创作徽标标志、广告标牌、车身贴和传单、模型绘制、插图描画、排版及分色输出等。CorelDRAW X4 SP2软件特色CorelDraw X4 相比两年前的 CorelDraw X3 加入了大量新特性,总计有50项以上,...

weixin_30346025的博客 8892

机器人控制算法九之 位姿描述与空间变换

机器人控制算法九之 位姿描述与空间变换

yohnyang的博客 1032

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 命令行运行带参数的Python脚本:sys.argv
下一篇: Linux 删除包含指定字符的文件夹
Robin_Pi
博客等级 码龄9年 2万+粉丝 632原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值