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, where classname is 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 MappingSubclass were to introduce a __update identifier since it is replaced with _Mapping__update in the Mapping class and _MappingSubclass__update in the MappingSubclass class 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() or eval() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr()setattr() and delattr(), 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的更多相关文章

  1. python学习小记

    python HTTP请求示例: # coding=utf-8 # more materials: http://docs.python-requests.org/zh_CN/latest/user/ ...

  2. Python学习小记(5)---Magic Method

    具体见The Python Language Reference 与Attribute相关的有 __get__ __set__ __getattribute__ __getattr__ __setat ...

  3. Python学习小记(3)---scope&namespace

    首先,函数里面是可以访问外部变量的 #scope.py def scope_test(): spam = 'scope_test spam' def inner_scope_test(): spam ...

  4. Python学习小记(1)---import小记

    在这种目录结构下,import fibo会实际导入fibo文件夹这个module λ tree /F 卷 Programs 的文件夹 PATH 列表 卷序列号为 BC56-3256 D:. │ fib ...

  5. Python学习小记(2)---[list, iterator, and, or, zip, dict.keys]

    1.List行为 可以用 alist[:] 相当于 alist.copy() ,可以创建一个 alist 的 shallo copy,但是直接对 alist[:] 操作却会直接操作 alist 对象 ...

  6. python 学习小记之冒泡排序

    lst =[11,22,44,2,1,5,7,8,3] for i in range(len(lst)):     i = 0     while i < len(lst)-1:         ...

  7. mongodb入门学习小记

    Mongodb 简单入门(个人学习小记) 1.安装并注册成服务:(示例) E:\DevTools\mongodb3.2.6\bin>mongod.exe --bind_ip 127.0.0.1 ...

  8. Python学习--04条件控制与循环结构

    Python学习--04条件控制与循环结构 条件控制 在Python程序中,用if语句实现条件控制. 语法格式: if <条件判断1>: <执行1> elif <条件判断 ...

  9. Python学习--01入门

    Python学习--01入门 Python是一种解释型.面向对象.动态数据类型的高级程序设计语言.和PHP一样,它是后端开发语言. 如果有C语言.PHP语言.JAVA语言等其中一种语言的基础,学习Py ...

随机推荐

  1. 共享excel工作簿

  2. 关于selenium无法在chrome中自动播放flash的问题

    最近用selenium写个小脚本,遇到flash不能自动播放问题 我遇到的情况,直接提示 请确认是否安装flash,其实已经安装,点击下载flash,然后提示是否允许. 整了好久,发现终极方法: ## ...

  3. Java 使用 UnixSocket 调用 Docker API

    在 Docker 官网查阅 API 调用方式 例如:查询正在运行的容器列表,HTTP 方式如下: $ curl --unix-socket /var/run/docker.sock http:/v1. ...

  4. Qt使用QAxObject快速批量读取Excel内容

    网上各种教程用的方法主要是如下这一句: QAxObject * range = worksheet->querySubObject("Cells(int,int)", 1, ...

  5. 利用Python进行博客图片压缩

    自己写博客的时候常常要插入一些手机拍的照片,都是几M的大小,每张手动压缩太费事了,于是根据自己博客的排版特点用Python写了一个简单的图片压缩脚本,功能是将博客图片生成缩略图,横屏的图片压缩为宽度最 ...

  6. 八、django学习之分组查询、F查询和Q查询

    分组查询.F查询和Q查询 分组查询 统计每个出版社出版的书籍的平均价格 第一种方式 obj = models.Book.objects.values('publishs_id').annotate(a ...

  7. 四、Django学习之关系表介绍及使用

    关系表介绍及使用 一对一关系 xx = models.OneToOneField(to='表名',to_field='字段名',on_delete=models.CASCADE) #on_delete ...

  8. React 函数生命周期

      React 函数生命周期基础 1 ,概念 在组件创建.到加载到页面上运行.以及组件被销毁的过程中,总是伴随着各种各样的事件,这些在组件特定时期,触发的事件,统称为组件的生命周期:* 2,组件生命周 ...

  9. HTML5的基础学习

    课前预习:HTML又被叫做超文本标记语言,它不是编程语言,是web中最微不足道的,但又是web中最微不足道的基石, 对零基础学习HTML的人员来说先认识HTML的标签和字体是必不可少的,万丈高楼平地起 ...

  10. python 利用selenium爬取百度文库的word文章

    今天学习如何使用selenium库来爬取百度文库里面的收费的word文档 from selenium import webdriver from selenium.webdriver.common.k ...