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
, whereclassname
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 theMapping
class and_MappingSubclass__update
in theMappingSubclass
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()
oreval()
does not consider the classname of the invoking class to be the current class; this is similar to the effect of theglobal
statement, 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 ...
随机推荐
- 8.JavaSE之变量、常量、作用域
变量variable: 变量是什么:就是内存中开辟的可以变化的量! Java是一种强类型语言,每个变量都必须声明其类型. Java变量是程序中最基本的存储单元,其要素包括变量名,变量类型,作用域 ...
- 异数OS 织梦师-云(五)-- 容器服务化,绿色拯救未来。
. 异数OS 织梦师-云(五)– 容器服务化,绿色拯救未来. 本文来自异数OS社区 github: https://github.com/yds086/HereticOS 异数OS社区QQ群: 652 ...
- spring boot 整合 swagger2
swagger2为了更好的管理api文档接口 swagger构建的api文档如下,清晰,避免了手写api诸多痛点 一,添加依赖 <!--swagger2的官方依赖--> <depen ...
- [bzoj1045] [洛谷P2512] [HAOI2008] 糖果传递
Description 有n个小朋友坐成一圈,每人有ai个糖果.每人只能给左右两人传递糖果.每人每次传递一个糖果代价为1. Input 第一行一个正整数nn<=1'000'000,表示小朋友的个 ...
- 「 从0到1学习微服务SpringCloud 」08 构建消息驱动微服务的框架 Spring Cloud Stream
系列文章(更新ing): 「 从0到1学习微服务SpringCloud 」01 一起来学呀! 「 从0到1学习微服务SpringCloud 」02 Eureka服务注册与发现 「 从0到1学习微服务S ...
- Hystrix 监控数据聚合 Turbine【Finchley 版】
原文地址:https://windmt.com/2018/04/17/spring-cloud-6-turbine/ 上一篇我们介绍了使用 Hystrix Dashboard 来展示 Hystrix ...
- CentOS7安装MySQL、Tomcat和GitBlit记录
一.安装MySQL 1.安装这个发布包 yum localinstall mysql-community-release-el6-5.noarch.rpm 可以通过下面的命令来确认这个仓库被成功添加: ...
- initramfs打包集成rootfs到image镜像及linux rootfs的正常启动
最近的项目中需要在仿真机haps及VDK上集成rootfs,中间遇到一些问题,在此整理记录以备忘. rootfs里面集成的busybox版本1.29.3 (buildroot环境中自带) kernel ...
- python,for循环的使用案例集
1.循环执行某一系列操作.将该操作定义为一个def,然后使用for去循环执行该操作 思路,先把操作定义为一个函数,在for循环执行这个函数 比如下面案例,把微信好友列表内的好友,循环的方式依次调整到第 ...
- lua 中 . 和 : 的区别
lua 中 . 和 : 的区别 首先在lua中使用":"定义的函数会自动传入一个名为self的变量,这个变量是隐含的,self同c++中的this一样,表示当前对象的指针:而&qu ...