The Python Tutorial之Class(一)

RSM 219 | CLASS 1 – TUTORIAL: Introduction to Financial ReportingR products.Ourmission istorgy.doany cashdividendsinthe16,39816,25317,57619,38444,55532,76434,89532,18029,80627,261329(5,399)8328331,4481,86896,77381,46253,82331,53640,21724,90613,6066,6302,6638,2978,087。 阅读详情

1. A Word About Names and Objects

  • Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages.
  • For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change.

理解name和object的关系是基础,这里name相当于指针,如果在函数内改变该对象的值,在函数外将会看到这种改变,理解这点需要简单敲些代码:

>>> def change(x,y):
		x=2
		y=y.append('a')

	
>>> x=1
>>> y=[0]
>>> change(x,y)
>>> x
1
>>> y
[0, 'a']
>>>

从结果来看,很明显y作为列表类型的变元,在函数中改变了值;而x引用的是1这个常量无法改变,所以打印结果还是1,但是在change函数中,确实将x赋值2,该x的也确实存在,只不过namespace空间不同而已。

2. Python Scopes and Namespaces

  • A namespace is a mapping from names to objects.
  • Examples of namespaces are:
  • the set of built-in names (containing functions such as abs(), and built-in exception names);
  • the global names in a module
  • the local names in a function invocation
  • the set of attributes of an object also form a namespace.
  • The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function maximize without confusion — users of the modules must prefix it with the module name.

笔者将引用内容稍微排版,这样就很清楚了。上面的例子中x指向1对象与x指向2对象的命名空间不同,前者处于global names,后者处于local names。接下来个概念更加的绕:

  • By the way, I use the word attribute for any name following a dot
  • for example, in the expression z.real, real is an attribute of the object z.
  • Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it. In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace!
    认为moudle的attributes和global names处于同一命名空间,注意回到Examples of namespaces部分再品味下

如果接受第一条的设定,那么第二条也很容易理解,看如下代码:

class function1 ()
    def fun ():
	    print("hello\n")

def function ()
    print("world\n")
# 保存为nametest.py
import nametest.py

之后对其的引用:nametest.function 或者nametest.function1都属于module自身的attribute的引用,而function与function1(名字)都处于global namespace。

Namespaces are created at different moments and have different lifetimes:

  • The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted.
  • The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits.
    • The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called main, so they have their own global namespace.
  • The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. Of course, recursive invocations each have their own local namespace.

上面的引用解释了几个问题:builtins模块的namespace在解释器启动的时候引入,永不被删除;_main_模块的namespace在解释器执行第一条语句时引入,持续到解释器退出;函数有自己的local namespace,该空间在函数调用时引入,函数返回或者异常抛出时删除。接下来看看scope:

A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
第一句话说namespace和scope的关系,不加限定词对一个对象的引用(xxx.xxx.object就是加限定词的意思)按照下面的顺序查找scope:

  • the innermost scope, which is searched first, contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
  • the next-to-last scope contains the current module’s global names
  • the outermost scope (searched last) is the namespace containing built-in names

然后官网手册列了下面两个列子:

  • If a name is declared global, then all references and assignments go directly to the middle scope containing the module’s global names.
  • To rebind variables found outside of the innermost scope, the nonlocal statement can be used; if not declared nonlocal, those variables are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).

敲敲代码解释一波:

#第一点
>>> def change(x):
		 global y
		 y=x

	 
>>> y=1
>>> change(10)
>>> y
10
>>> 
#第二点
>>> def change(x):
	    y=2;
	    def change1(z):
	        y=z
	    change1(x)
	    print(y)

>>> change(1)
2
>>> def change(x):
	    y=2;
	    def change1(z):
	        nonlocal y #言简意赅的说就是nonlocal改变了y的namespace
	        y=z
	    change1(x)
	    print(y)

>>> change(1)
1

Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. Class definitions place yet another namespace in the local scope.

先理解上面的引用,local scope指local namespace或者global namespace,class的定义会开辟另一个namespace在global namespace(又叫local scope)。然后看下面的引用,特别第三点:

It is important to realize that scopes are determined textually:

  • the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time.
  • A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement del x removes the binding of x from the namespace referenced by the local scope.
  • In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope. (The global statement can be used to indicate that particular variables live in the global scope.)这里local scope指global namespaces,括号里面的情况是local namespaces的情况

3. Scopes and Namespaces Example

最后看看官网的例子:

def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

结果:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

经过上面的学习一路,很容易解释这种结果,特别最后After global assignment: nonlocal spam,因为此时spam的引用首先查找的是scope_test的local namespace。

4. 总结

在这一篇理解了什么是namespace及namespace的分类,scope和namespace的关系,最后结合了一个例子充分理解上述理论的实际情况。实际上很多python入门书或者课程,都会隔过去这里,只是介绍下nonlocal或者global的用法。理解这里对于后续编写脚本至关重要。

Grok CLI教程:命令行AI工具与/tutorial交互式学习指南 命令行界面(CLI)作为开发者与系统交互的核心工具,通过文本指令实现高效操作和自动化。其工作原理基于命令解析、进程调用和结果返回,在DevOps和持续集成中具有重要技术价值。随着AI技术的发展,CLI工具开始集成大语言模型能力,为开发者提供智能代码审查、自动化脚本生成等应用场景。xAI推出的Grok CLI正是这一趋势的典型代表,特别是其创新的/tutorial命令,通过交互式学习模式降低AI工具使用门槛。该功能采用渐进式教学,结合API集成实战,帮助开发者快速掌握AI能力集成技能,显著提升开发效率和学习效 阅读详情

相关推荐

Python tutorial 3.3(中文版)

Python tutorial 3.3版本,学习python的非常好的资料,与大家一起学习成长

Python tutorial笔记 class

Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes a derived class can override any methods of its base

阿张的代码诗社 486

国内免魔法接入Grok API,打造智能QQ机器人实战指南

大型语言模型(LLM)通过API接口为开发者提供了强大的自然语言处理能力,其核心原理是基于海量数据训练的深度神经网络,能够理解和生成类人文本。这一技术价值在于显著降低了AI应用开发门槛,使开发者无需从零训练模型即可快速集成智能对话、内容生成等功能。在即时通讯、智能客服、自动化工具等应用场景中,LLM API能有效提升交互体验与效率。本文聚焦于如何通过稳定的第三方API服务,绕开网络访问限制,将xAI推出的Grok模型接入国内网络环境,并结合NoneBot2框架与go-cqhttp,实现一个功能完整的智能QQ

weixin_30607125的博客 342

python tutorial是什么意思_方法类Python Tutorial(九):类 方法类

题记:写这篇博客要主是加深自己对方法类的认识和总结实现算法时的一些验经和训教,如果有错误请指出,万分感谢。与其它编程语言比相,Python的类机制加添了最小的新法语和语义。它是C++和Modula-3中的类机制的混合。Python的类供提了面向对象编程的有所的准标特性,类继承机制许允有多个基类,一个类子可以重写基类中的任何方法,一个方法可以调用基类面里的同名方法。对象可以含包恣意数量和种类的数据。...

weixin_30062621的博客 573

Ascend C 算子开发遇到的问题及解决方法

在学习Ascend C算子开发进阶课程的时候,进行Ascend C自定义算子工程、算子调用等实验,在开发环境中遇到了一些问题,在这里记录一下。首先如果在启智社区CANN版本为6.3 ,要进行Ascend C算子开发,需要更新CANN版本。

qq_45257495的博客 5110

Vivado里LDPC IP核怎么配?手把手教你从6144bit数据到完整参数设置

本文详细介绍了在Vivado中配置LDPC IP核的完整流程,从6144bit数据的参数计算到实际IP核设置。通过分析基本图选择、扩展因子计算和移位参数确定等关键步骤,帮助工程师高效完成LDPC编译码的硬件实现,并提供了时序控制、仿真验证和性能优化的实用技巧。

weixin_30352645的博客 519

python示例_带有示例的Python类教程

python示例Class is a popular paradigm used in programming language. Object oriented programming is created the class structures in order to work programming structures like a real world objects. Class ...

cunjiu9486的博客 310

C#工业相机毫秒级采集与处理:实现7x24小时稳定运行

在机器视觉行业摸爬滚打这么多年,我见过太多这样的项目:工程师用C#接了海康或巴斯勒的相机,写个GrabLoop,在实验室里跑个半小时一切正常。结果一到客户现场,7x24小时连轴转,问题就全暴露了——运行8小时后内存缓慢上涨,最终OOM崩溃每隔几分钟出现一次200ms的采集卡顿,导致飞拍漏检CPU占用率莫名飙高,但帧率却上不去程序假死,相机SDK回调不再触发,只能重启这些问题的根源,往往不是相机硬件不行,也不是算法太慢,而是C#托管运行时与工业相机底层驱动之间的“工程摩擦”。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 197

python关于namespace和scope(命名空间和作用域)

1.namespace (1)定义 A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performan...

Mr_Slower的博客 1062

RK3568平台开发系列讲解(音频篇)配置声卡

📢本篇文章介绍如何配置声卡。

内核笔记 2452

kaggle学习笔记-餐厅数据挖掘

分析Zomato数据集的基本思想是为了公平地了解影响在班加罗尔不同地方建立不同类型餐厅的因素,每个餐厅的总评级,班加罗尔是这样一个城市,拥有超过12,000家餐厅,餐厅供应来自世界各地的菜肴。每天都有新的餐馆开业,这个行业还没有饱和,需求也在与日俱增。然而,尽管需求不断增加,新餐馆却很难与老牌餐馆竞争。大多数餐厅都供应同样的食物。班加罗尔是印度的IT之都。这里的大多数人主要依靠餐馆的食物,因为他们没有时间自己做饭。由于对餐馆的需求如此巨大,因此研究一个地方的人口统计学就变得很重要。

优快云XXCQ的博客 1862

The Python Tutorial之Class(三)

1. Inheritance The name BaseClassName must be defined in a scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can b...

LoveStackover的博客 221

【2026年华为秋招(AI)-2月4日-第一题(100分)- 选择题】(题目+思路+Java&C++&Python解析+在线测试)

本文摘要:本文包含20道选择题,涵盖机器学习、线性代数、Transformer架构、概率统计等多个领域。题目涉及正交矩阵性质、Transformer注意力机制、聚类距离度量、ReAct框架、Softmax函数、混淆矩阵计算、Flash-Attention优化、位置编码、期望计算、归一化方法、矩阵迭代法、矩阵秩、大模型架构、神经网络推理、泊松流性质、SVM核函数以及聚类算法等知识点。每道题均提供解析,帮助理解核心概念和解题思路。

m0_73659489的博客 126

The Python Tutorial之Class(二)

1. Class Objects When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, f...

LoveStackover的博客 357

从通用到定制:营销Agent如何跨越数据鸿沟,实现对话SOP的个性化飞跃

从通用到定制:营销Agent如何跨越数据鸿沟,实现对话SOP的个性化飞跃

丨汀、的博客 656

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

如何快速入门Python爬虫:Easy-scraping-tutorial基础教程

想要快速掌握Python爬虫技术?Easy-scraping-tutorial项目为你提供了一套完整而简单的Python网络爬虫教程代码。这个开源项目通过实际案例和循序渐进的教学方式,帮助初学者轻松入门网页数据抓取技术。无论你是数据分析师、研究人员还是开发者,学习Python爬虫都能让你从海量网页中高效提取有价值的信息。🚀 ## 📚 什么是Python爬虫? Python爬虫是一种自动化程

gitblog_00709的博客 1064

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

React 服务端跨请求 LRU 缓存实战:解析 preguntas-entrevista-react 中的 Vercel 缓存规则

本篇文章以 preguntas-entrevista-react 仓库内 `.agents/skills/vercel-react-best-practices` 技能包中的 `server-cache-lru` 规则为骨架,系统讲解 React/Next.js 服务端场景下跨请求 LRU 缓存的实现方案:为什么 `React.cache()` 不够用、如何用 `lru-cache` 构建可复用的

gitblog_00406的博客 1080

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Python 3.3 Tutorial Notes - 7:Class

1. Allow multiple base classes2. namespace: Most namespaces are currently implemented as Python dictionaries3. attribute:      3.1 for any name following a dot — for example, in the expression z.real 

NonStatic的博客 474

The Python Tutorial 9——Classes

Python类概况:多继承、override、多态 9.1. A Word About Names and Objects 9.2. Python Scopes and Namespaces 三种namespace,不同namespace间同名member互不影响 A namespace is a mapping from names to objects. Most namesp

yangcs2009的专栏 711

class node python,ROS/Tutorials

Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add app...

weixin_35675101的博客 279

图片批量下载实战:Easy-scraping-tutorial教你自动化抓取网络图片

想要快速批量下载网页上的精美图片吗?Python爬虫技术可以帮你实现自动化图片抓取!今天我们将通过 **Easy-scraping-tutorial** 这个开源教程项目,手把手教你如何用Python轻松实现图片批量下载。无论你是设计师需要收集素材,还是普通用户想要保存网页图片,这个简单实用的Python网络爬虫教程都能帮你快速上手。😊 ## 📸 为什么需要图片批量下载? 在日常工作和学习

gitblog_00525的博客 590

CSS选择器实战指南:Easy-scraping-tutorial精准定位网页元素

想要从海量网页中精准提取数据?CSS选择器是你的必备利器!😊 在Python网络爬虫中,CSS选择器是实现**网页元素精准定位**的核心技术。通过Easy-scraping-tutorial项目,即使是编程新手也能快速掌握这一强大工具。本文将带你深入了解CSS选择器的实战应用,让你轻松应对各种网页数据提取需求。 ## 📊 为什么CSS选择器如此重要? 在网页爬虫开发中,**CSS选择器**

gitblog_00534的博客 337

python tutorial 学习笔记(六)class

class ClassName( SuperClass ) : A new name space is created, thus all assignments to local variables go into this new namespace. When a class definitition ends, a class object is created. attribute names: __doc__( the fist multil-line string ), __cl

rea_1121的专栏 526

REST-tutorial安全指南:实现HTTP认证保护API接口

在当今API驱动的开发环境中,保护API接口安全至关重要。REST-tutorial项目提供了一个基于Python的REST API服务器和Javascript客户端,本指南将详细介绍如何通过HTTP认证机制保护API接口,防止未授权访问。 ## 为什么需要API认证? API接口作为应用程序的入口点,一旦缺乏适当的安全措施,可能导致敏感数据泄露、恶意攻击或服务滥用。REST-tutorial

gitblog_00499的博客 397

Python Programming with the Java(TM) Class Libraries: A Tutorial for Building Web and Enterprise App

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.youkuaiyun.com/topmvp - topmvpPython and Java are natural team-mates. Using Python together with the Java class libraries, developers at al

TopMVP 810

Structured Output in the MCP Python SDK: Your Return Type Annotation Is the Output Schema

这是一篇面向 MCP(Model Context Protocol)服务端开发者的技术指南,聚焦 python-sdk 中 Tool 的 **structured output(结构化输出)** 机制:SDK 会从你已写好的返回类型注解(return type annotation)自动推导出 `output_schema`,并将每一次 Tool 调用结果同时以 `content`(文本,供模型阅

gitblog_00044的博客 489
上一篇: The Python Tutorial之Class(二)
下一篇: DSAA之图论Dijkstra(贪婪算法)(五)
LoveStackover
博客等级 码龄9年 14粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值