Python学习小记(4)---class
1.名称修改机制
大概是会对形如 __parm 的成员修改为 _classname__spam
9.6. Private Variables
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g.
_spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form
__spam(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam, whereclassnameis the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable) def update(self, iterable):
for item in iterable:
self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)The above example would work even if
MappingSubclasswere to introduce a__updateidentifier since it is replaced with_Mapping__updatein theMappingclass and_MappingSubclass__updatein theMappingSubclassclass respectively.Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.
Notice that code passed to
exec()oreval()does not consider the classname of the invoking class to be the current class; this is similar to the effect of theglobalstatement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies togetattr(),setattr()anddelattr(), as well as when referencing__dict__directly.
试验结果如下
class Mapping:
def func(self):
print('function_in_Mapping')
__func = func
class MappingSubclass(Mapping):
def func(self):
print('function_in_MappingSubclass')
__func = func c = Mapping()
c.func()
e = MappingSubclass()
e.func()
e._Mapping__func()
e._MappingSubclass__func()
E:\Coding\Python>python class_test.py
function_in_Mapping
function_in_MappingSubclass
function_in_Mapping
function_in_MappingSubclass
而直接调用 c.__func() 会报错,表明这个属性并不存在,因为已经被改写成了 _Mapping__func 或 _MappingSubclass__func
class Mapping:
def func(self):
print('function_in_Mapping')
__func = func
class MappingSubclass(Mapping):
def func(self):
print('function_in_MappingSubclass')
__func = func
c = Mapping()
c.func()
e = MappingSubclass()
e.func()
e._Mapping__func()
e._MappingSubclass__func() c.__func()
e.__func()
E:\Coding\Python>python class_test.py
function_in_Mapping
function_in_MappingSubclass
function_in_Mapping
function_in_MappingSubclass
Traceback (most recent call last):
File "class_test.py", line 16, in <module>
c.__func()
AttributeError: 'Mapping' object has no attribute '__func'
Python学习小记(4)---class的更多相关文章
- python学习小记
python HTTP请求示例: # coding=utf-8 # more materials: http://docs.python-requests.org/zh_CN/latest/user/ ...
- Python学习小记(5)---Magic Method
具体见The Python Language Reference 与Attribute相关的有 __get__ __set__ __getattribute__ __getattr__ __setat ...
- Python学习小记(3)---scope&namespace
首先,函数里面是可以访问外部变量的 #scope.py def scope_test(): spam = 'scope_test spam' def inner_scope_test(): spam ...
- Python学习小记(1)---import小记
在这种目录结构下,import fibo会实际导入fibo文件夹这个module λ tree /F 卷 Programs 的文件夹 PATH 列表 卷序列号为 BC56-3256 D:. │ fib ...
- Python学习小记(2)---[list, iterator, and, or, zip, dict.keys]
1.List行为 可以用 alist[:] 相当于 alist.copy() ,可以创建一个 alist 的 shallo copy,但是直接对 alist[:] 操作却会直接操作 alist 对象 ...
- python 学习小记之冒泡排序
lst =[11,22,44,2,1,5,7,8,3] for i in range(len(lst)): i = 0 while i < len(lst)-1: ...
- mongodb入门学习小记
Mongodb 简单入门(个人学习小记) 1.安装并注册成服务:(示例) E:\DevTools\mongodb3.2.6\bin>mongod.exe --bind_ip 127.0.0.1 ...
- Python学习--04条件控制与循环结构
Python学习--04条件控制与循环结构 条件控制 在Python程序中,用if语句实现条件控制. 语法格式: if <条件判断1>: <执行1> elif <条件判断 ...
- Python学习--01入门
Python学习--01入门 Python是一种解释型.面向对象.动态数据类型的高级程序设计语言.和PHP一样,它是后端开发语言. 如果有C语言.PHP语言.JAVA语言等其中一种语言的基础,学习Py ...
随机推荐
- Java入门 - 高级教程 - 04.序列化
原文地址:http://www.work100.net/training/java-serialization.html 更多教程:光束云 - 免费课程 序列化 序号 文内章节 视频 1 概述 2 序 ...
- [ PyQt入门教程 ] PyQt5中多线程模块QThread使用方法
本文主要讲解使用多线程模块QThread解决PyQt界面程序唉执行耗时操作时,程序卡顿出现的无响应以及界面输出无法实时显示的问题.用户使用工具过程中出现这些问题时会误以为程序出错,从而把程序关闭.这样 ...
- 月经贴 】 Csharp in depth
让你 真正 喜欢 上 C# 编译器 准备 为你 上演 的 奇迹. C# 3 中 相对 乏味 的 一些 特性 开始. 自动 实现 的 属性 和 简化 的 初始化, 有一个 私 有的 无 参 构造 函 ...
- Shell命令整理
Shell命令 一.认识Shell 在Linux系统中,Shell充当着用户与Linux内核的桥梁,俗称壳保护着Linux内核,同时也负责完成用户与内核之间的交互. 当用户需要与内核交互时,将命令传递 ...
- Ogre3d 1.7.x 的 RTShaderSystem的一个BUG
来源:http://www.ogre3d.org/forums/viewtopic.php?f=2&t=63644 表现:使用dx的shader可能会造成程序崩溃. 在文件OgreShader ...
- 张旭个人第4次作业—Alpha项目测试
课程 软件工程实践 作业要求 个人第四次作业 团队名称 C#软工造梦厂 作业目标 运行其他组的项目找出问题及提出建议 一.测试人信息 姓名 张旭 学号 201731024123 团队名称 C#软工造梦 ...
- 03--java--DOS编译运行输出Java,Hi!
lalala.... 1.新建文本文档,将扩展名改成.java为后缀的文件 2.利用记事本打开.java文件,进行编写保存 3.启动dos窗口,进入到.java文件所在目录中 4.使用"ja ...
- 爬虫之pyspider 安装
解决方法: 利用wheel安装 S1: pip install wheelS2: 进入www.lfd.uci.edu/~gohlke/pythonlibs/,Ctrl + F查找pycurl S3:这 ...
- 数据结构与算法 --- js描述队列
js描述队列 队列的特性是只能在队尾插入元素,在队首删除元素,先进先出: 队列被用在很多地方,比如提交操作系统执行的一系列进程,打印任务池,模拟现实中的排队: //队列类 function Queue ...
- Python使用requests发送post请求的三种方式
1.我们使用postman进行接口测试的时候,发现POST请求方式的编码有3种,具体的编码方式如下: A:application/x-www-form-urlencoded ==最常见的post提交数 ...