Python面向对象进阶2.html

:first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0,0,.1);border-radius:3px}iframe{border:0}figure{-webkit-margin-before:0;-webkit-margin-after:0;-webkit-margin-start:0;-webkit-margin-end:0}kbd{border:1px solid #aaa;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;-moz-box-shadow:1px 2px 2px #ddd;-webkit-box-shadow:1px 2px 2px #ddd;box-shadow:1px 2px 2px #ddd;background-color:#f9f9f9;background-image:-moz-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:-o-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:-webkit-linear-gradient(top,#eee,#f9f9f9,#eee);background-image:linear-gradient(top,#eee,#f9f9f9,#eee);padding:1px 3px;font-family:inherit;font-size:.85em}.oembeded .oembed_photo{display:inline-block}img[data-echo]{margin:25px 0;width:100px;height:100px;background:url(../img/ajax.gif) center center no-repeat #fff}.spinner{display:inline-block;width:10px;height:10px;margin-bottom:-.1em;border:2px solid rgba(0,0,0,.5);border-top-color:transparent;border-radius:100%;-webkit-animation:spin 1s infinite linear;animation:spin 1s infinite linear}.spinner:after{content:'';display:block;width:0;height:0;position:absolute;top:-6px;left:0;border:4px solid transparent;border-bottom-color:rgba(0,0,0,.5);-webkit-transform:rotate(45deg);transform:rotate(45deg)}@-webkit-keyframes spin{to{-webkit-transform:rotate(360deg)}}@keyframes spin{to{transform:rotate(360deg)}}p.toc{margin:0!important}p.toc ul{padding-left:10px}p.toc>ul{padding:10px;margin:0 10px;display:inline-block;border:1px solid #ededed;border-radius:5px}p.toc li,p.toc ul{list-style-type:none}p.toc li{width:100%;padding:0;overflow:hidden}p.toc li a::after{content:"."}p.toc li a:before{content:"• "}p.toc h5{text-transform:uppercase}p.toc .title{float:left;padding-right:3px}p.toc .number{margin:0;float:right;padding-left:3px;background:#fff;display:none}input.task-list-item{margin-left:-1.62em}.markdown{font-family:"Hiragino Sans GB","Microsoft YaHei",STHeiti,SimSun,"Lucida Grande","Lucida Sans Unicode","Lucida Sans",'Segoe UI',AppleSDGothicNeo-Medium,'Malgun Gothic',Verdana,Tahoma,sans-serif;padding:20px}.markdown a{text-decoration:none;vertical-align:baseline}.markdown a:hover{text-decoration:underline}.markdown h1{font-size:2.2em;font-weight:700;margin:1.5em 0 1em}.markdown h2{font-size:1.8em;font-weight:700;margin:1.275em 0 .85em}.markdown h3{font-size:1.6em;font-weight:700;margin:1.125em 0 .75em}.markdown h4{font-size:1.4em;font-weight:700;margin:.99em 0 .66em}.markdown h5{font-size:1.2em;font-weight:700;margin:.855em 0 .57em}.markdown h6{font-size:1em;font-weight:700;margin:.75em 0 .5em}.markdown h1+p,.markdown h1:first-child,.markdown h2+p,.markdown h2:first-child,.markdown h3+p,.markdown h3:first-child,.markdown h4+p,.markdown h4:first-child,.markdown h5+p,.markdown h5:first-child,.markdown h6+p,.markdown h6:first-child{margin-top:0}.markdown hr{border:1px solid #ccc}.markdown p{margin:1em 0;word-wrap:break-word}.markdown ol{list-style-type:decimal}.markdown li{display:list-item;line-height:1.4em}.markdown blockquote{margin:1em 20px}.markdown blockquote>:first-child{margin-top:0}.markdown blockquote>:last-child{margin-bottom:0}.markdown blockquote cite:before{content:'\2014 \00A0'}.markdown .code{border-radius:3px;word-wrap:break-word}.markdown pre{border-radius:3px;word-wrap:break-word;border:1px solid #ccc;overflow:auto;padding:.5em}.markdown pre code{border:0;display:block}.markdown pre>code{font-family:Consolas,Inconsolata,Courier,monospace;font-weight:700;white-space:pre;margin:0}.markdown code{border-radius:3px;word-wrap:break-word;border:1px solid #ccc;padding:0 5px;margin:0 2px}.markdown img{max-width:100%}.markdown mark{color:#000;background-color:#fcf8e3}.markdown table{padding:0;border-collapse:collapse;border-spacing:0;margin-bottom:16px}.markdown table tr td,.markdown table tr th{border:1px solid #ccc;margin:0;padding:6px 13px}.markdown table tr th{font-weight:700}.markdown table tr th>:first-child{margin-top:0}.markdown table tr th>:last-child{margin-bottom:0}.markdown table tr td>:first-child{margin-top:0}.markdown table tr td>:last-child{margin-bottom:0}.github{padding:20px;font-family:"Helvetica Neue",Helvetica,"Hiragino Sans GB","Microsoft YaHei",STHeiti,SimSun,"Segoe UI",AppleSDGothicNeo-Medium,'Malgun Gothic',Arial,freesans,sans-serif;font-size:15px;background:#fff;line-height:1.6;-webkit-font-smoothing:antialiased}.github a{color:#3269a0}.github a:hover{color:#4183c4}.github h2{border-bottom:1px solid #e6e6e6;line-height:1.6}.github h6{color:#777}.github hr{border:1px solid #e6e6e6}.github pre>code{font-size:.9em;font-family:Consolas,Inconsolata,Courier,monospace}.github blockquote>code,.github h1>code,.github h2>code,.github h3>code,.github h4>code,.github h5>code,.github h6>code,.github li>code,.github p>code,.github td>code{background-color:rgba(0,0,0,.07);font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;font-size:85%;padding:.2em .5em;border:0}.github blockquote{border-left:4px solid #e6e6e6;padding:0 15px;font-style:italic}.github table{background-color:#fafafa}.github table tr td,.github table tr th{border:1px solid #e6e6e6}.github table tr:nth-child(2n){background-color:#f2f2f2}.hljs-comment,.hljs-title{color:#9c9491}.css .hljs-class,.css .hljs-id,.css .hljs-pseudo,.hljs-attribute,.hljs-regexp,.hljs-tag,.hljs-variable,.html .hljs-doctype,.ruby .hljs-constant,.xml .hljs-doctype,.xml .hljs-pi,.xml .hljs-tag .hljs-title{color:#f22c40}.hljs-built_in,.hljs-constant,.hljs-literal,.hljs-number,.hljs-params,.hljs-pragma,.hljs-preprocessor{color:#df5320}.css .hljs-rules .hljs-attribute,.hljs-ruby .hljs-class .hljs-title{color:#d5911a}.hljs-header,.hljs-inheritance,.hljs-string,.hljs-value,.ruby .hljs-symbol,.xml .hljs-cdata{color:#5ab738}.css .hljs-hexcolor{color:#00ad9c}.coffeescript .hljs-title,.hljs-function,.javascript .hljs-title,.perl .hljs-sub,.python .hljs-decorator,.python .hljs-title,.ruby .hljs-function .hljs-title,.ruby .hljs-title .hljs-keyword{color:#407ee7}.hljs-keyword,.javascript .hljs-function{color:#6666ea}.hljs{display:block;overflow-x:auto;background:#2c2421;color:#a8a19f;padding:.5em;-webkit-text-size-adjust:none}.coffeescript .javascript,.javascript .xml,.tex .hljs-formula,.xml .css,.xml .hljs-cdata,.xml .javascript,.xml .vbscript{opacity:.5}.MathJax_Hover_Frame{border-radius:.25em;-webkit-border-radius:.25em;-moz-border-radius:.25em;-khtml-border-radius:.25em;box-shadow:0 0 15px #83A;-webkit-box-shadow:0 0 15px #83A;-moz-box-shadow:0 0 15px #83A;-khtml-box-shadow:0 0 15px #83A;border:1px solid #A6D!important;display:inline-block;position:absolute}.MathJax_Hover_Arrow{position:absolute;width:15px;height:11px;cursor:pointer}#MathJax_About{position:fixed;left:50%;width:auto;text-align:center;border:3px outset;padding:1em 2em;background-color:#DDD;color:#000;cursor:default;font-family:message-box;font-size:120%;font-style:normal;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;z-index:201;border-radius:15px;-webkit-border-radius:15px;-moz-border-radius:15px;-khtml-border-radius:15px;box-shadow:0 10px 20px gray;-webkit-box-shadow:0 10px 20px gray;-moz-box-shadow:0 10px 20px gray;-khtml-box-shadow:0 10px 20px gray;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}.MathJax_Menu{position:absolute;background-color:#fff;color:#000;width:auto;padding:2px;border:1px solid #CCC;margin:0;cursor:default;font:menu;text-align:left;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;z-index:201;box-shadow:0 10px 20px gray;-webkit-box-shadow:0 10px 20px gray;-moz-box-shadow:0 10px 20px gray;-khtml-box-shadow:0 10px 20px gray;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}.MathJax_MenuItem{padding:2px 2em;background:0 0}.MathJax_MenuArrow{position:absolute;right:.5em;color:#666}.MathJax_MenuActive .MathJax_MenuArrow{color:#fff}.MathJax_MenuArrow.RTL{left:.5em;right:auto}.MathJax_MenuCheck{position:absolute;left:.7em}.MathJax_MenuCheck.RTL{right:.7em;left:auto}.MathJax_MenuRadioCheck{position:absolute;left:1em}.MathJax_MenuRadioCheck.RTL{right:1em;left:auto}.MathJax_MenuLabel{padding:2px 2em 4px 1.33em;font-style:italic}.MathJax_MenuRule{border-top:1px solid #CCC;margin:4px 1px 0}.MathJax_MenuDisabled{color:GrayText}.MathJax_MenuActive{background-color:Highlight;color:HighlightText}.MathJax_Menu_Close{position:absolute;width:31px;height:31px;top:-15px;left:-15px}#MathJax_Zoom{position:absolute;background-color:#F0F0F0;overflow:auto;display:block;z-index:301;padding:.5em;border:1px solid #000;margin:0;font-weight:400;font-style:normal;text-align:left;text-indent:0;text-transform:none;line-height:normal;letter-spacing:normal;word-spacing:normal;word-wrap:normal;white-space:nowrap;float:none;box-shadow:5px 5px 15px #AAA;-webkit-box-shadow:5px 5px 15px #AAA;-moz-box-shadow:5px 5px 15px #AAA;-khtml-box-shadow:5px 5px 15px #AAA;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')}#MathJax_ZoomOverlay{position:absolute;left:0;top:0;z-index:300;display:inline-block;width:100%;height:100%;border:0;padding:0;margin:0;background-color:#fff;opacity:0;filter:alpha(opacity=0)}#MathJax_ZoomFrame{position:relative;display:inline-block;height:0;width:0}#MathJax_ZoomEventTrap{position:absolute;left:0;top:0;z-index:302;display:inline-block;border:0;padding:0;margin:0;background-color:#fff;opacity:0;filter:alpha(opacity=0)}.MathJax_Preview{color:#888}#MathJax_Message{position:fixed;left:1px;bottom:2px;background-color:#E6E6E6;border:1px solid #959595;margin:0;padding:2px 8px;z-index:102;color:#000;font-size:80%;width:auto;white-space:nowrap}#MathJax_MSIE_Frame{position:absolute;top:0;left:0;width:0;z-index:101;border:0;margin:0;padding:0}.MathJax_Error{color:#C00;font-style:italic}footer{position:fixed;font-size:.8em;text-align:right;bottom:0;margin-left:-25px;height:20px;width:100%}
-->


title: Python 面向对象进阶2
tags: Python

1 setitem getitem delitem

把 对象操作属性模拟字典格式

class Foo:
def __init__(self,name):
self.name=name
def __getitem__(self, item):
return self.__dict__[item] # getitem 通过return返回
def __setitem__(self, key, value):
self.__dict__[key]=value # 真正操作的是字典中的
def __delitem__(self,key):
# self.__dict__.pop[key] # 把字典中的删除
self.__dict__.pop(key) # pop是个函数 f=Foo('aaa') # 实例化
print(f['name']) # 这是getitem
f['age']=18 # setitem
print(f.__dict__)

打印结果:
{‘name’: ‘aaa’, ‘age’: 18}

f=Foo('aaa')
print(f['name'])
f['age']=18
del f['age'] # delitem
del f['name']
print(f.__dict__) # 通过查看对象的名称空间可

结果:

2 _slots_

slots是一个类变量,变量的值可以是列表、字典、字符串、可迭代对象,用的是类的名称空间,是共享的,对象没有自己的名称空间,省内存

class People:
__slots__=['x','y','z'] #设置相应的属性
p=People()
print(People.__dict__)
p.x=1
p.y=2
p.z=3
print(p.x,p.y,p.z)
# print(p.__dict__)
p1=People()
p1.x=11
p1.y=21
p1.z=31
print(p1.x,p1.y,p1.z)

结果:
1 2 3
11 21 31

slots应用:字典会占用大量内存,如果一个类的属性很少,但是有很多类,为了节省内存可以使用slots代替dict

3 __next和 ___iter__ 实现迭代器协议

可迭代对象内置iter方法,可迭代对象赋值就是一个迭代器,迭代器可以使用next方法

from collections import Iterator,Iterable
class Foo:
def __init__(self,start):
self.start=start
def __iter__(self):
return self
def __next__(self):
if self.start > 10:
raise StopIteration
n = self.start
self.start+=1
return n f=Foo(5)
# print(next(f))
for i in f:
print(i)

4 _doc_

class Foo:
'这是描述信息'
pass
print(Foo.__doc__) # 打印的结果就是函数的注释信息

无法继承

class Foo:
'这是描述信息'
pass
class Bar(Foo):
pass
print(Bar.__dic__)

结果:
type object ‘Bar’ has no attribute ‘dic

5 _module 和 __class__

module 表示当前操作的对象在那个模块

class 表示当前操作的对象的类是什么

class Foo:
'这是描述信息'
pass
class Bar(Foo):
pass
# print(Bar.__dic__)
b=Bar()
print(b.__module__)
print(b.__class__)
print(Bar.__class__)
print(Foo.__class__)

结果:
main
class ‘main.Bar’>
class ‘type’>
class ‘type’>

6 _del_ 析构方法

但对象在内存中被释放时,自动触发_del_

class Foo(object):
"""docstring for Foo"""
def __del__(self):
print("zhi xing ")
f1 = Foo()
del f1
print('----')

文件操作

class Open:
def __init__(self,filepath,mode='r',encoding='utf-8'):
self.x = open(filepath,mode=mode,encoding=encoding)
# self.x = open(filepath,mode=mode,encoding=encoding)
self.filepath =filepath
self.mode=mode
self.encoding=encoding
def write(self,line):
self.x.write(line)
def __getattr__(self, item):
return getattr(self.x,item)
def __del__(self):
self.x.close()
f=Open('a.txt','w')
del f

7 __enter__ 和 __exit__上下文管理协议

上下文管理协议,即with语句,为了让一个对象兼容with语句必须在对象中声明enteriter

Python面向对象进阶(二)的更多相关文章

  1. Python 面向对象进阶(二)

    1. 垃圾回收 小整数对象池 Python对小整数的定义是 [-5, 257),这些整数对象是提前建立好的; 在一个Python程序中,所有位于这个范围内的整数,使用的都是同一个对象; 单个字符共用对 ...

  2. Python面向对象进阶和socket网络编程-day08

    写在前面 上课第八天,打卡: 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __i ...

  3. Python面向对象进阶和socket网络编程

    写在前面 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __init__(self ...

  4. Python开发【第七篇】:面向对象 和 python面向对象进阶篇(下)

    Python开发[第七篇]:面向对象   详见:<Python之路[第五篇]:面向对象及相关> python 面向对象(进阶篇)   上一篇<Python 面向对象(初级篇)> ...

  5. python面向对象进阶(八)

    上一篇<Python 面向对象初级(七)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  6. python 面向对象进阶之内置方法

    一 isinstance(obj,cls)和issubclass(sub,super) 1.1,isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(obj ...

  7. Python 面向对象 (进阶篇)

    <Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用(可 ...

  8. python面向对象进阶

    前言 上节大话python面向对象对面向对象有了一些了解,这次就不用大话风格了 (ps:真心不好扯啊) isinstance与issubclass isinstance(obj,cls)检查是否obj ...

  9. Python基础之面向对象进阶二

    一.__getattribute__ 我们一看见getattribute,就想起来前面学的getattr,好了,我们先回顾一下getattr的用法吧! class foo: def __init__( ...

随机推荐

  1. 洛谷P3572 [POI2014]PTA-Little Bird

    P3572 [POI2014]PTA-Little Bird 题目描述 In the Byteotian Line Forest there are nn trees in a row. On top ...

  2. IT兄弟连 JavaWeb教程 经典案例

    案例需求:编写一个jsp servlet程序,在login.jsp发起login.do登录请求,当输入的用户名是abc密码是123时,则判断是登录成功,其它暂时认为是登录失败.当用户登录成功时,将用户 ...

  3. C 语言实例 - 输出九九乘法口诀表

    C 语言实例 - 输出九九乘法口诀表 使用嵌套 for 循环输出九九乘法口诀表. 实例 #include<stdio.h> int main(){ //外层循环变量,控制行 ; //内层循 ...

  4. 运用html常用标签和css定位等学做模仿百度导航页面

    导航部分文字链接,鼠标触碰变颜色,除百度logo引用图片外,其它均代码编写.注释部分是一开始用的百度一下截图做的按钮,后来用div填充颜色写了一个按钮.效果图如下. HTML代码如下: <!DO ...

  5. struts2.5+框架使用通配符与动态方法

    概述:struts2.5以后加强了安全性,下面就是安全配置引发的问题 通配符: 在学习struts框架时经常会使用到通配符调用方法,如下: <package name="usercru ...

  6. easyui datagrid编辑时编辑框自动获取焦点

    onDblClickCell:function(rowIndex, field, val){//双击单元格监听器 $(this).datagrid('beginEdit',rowIndex);//开启 ...

  7. 11.联结表---SQL

    说明:使用交互式DBMS工具重要的是,要理解联结不是物理实体.换句话说,它在实际的数据库表中并不存在.DBMS会根据需要建立联结,它在查询执行期间一直存在. 一.等值语法:SELECT 字段 FROM ...

  8. Django之Form的ModelForm

    form与model的终极结合. from django import forms class BookForm(forms.ModelForm): class Meta: model = model ...

  9. [软件工程基础]Alpha 阶段发布说明

    新功能 增加了题库界面,其上有历届考试资料 系统已知的问题和限制 物理实验报告的收藏功能还无法使用 物理实验报告还不能评论 题库界面显示有些问题 最主要的生成实验报告功能在绝大多数安卓平台上显示&qu ...

  10. 牛客假日团队赛2 G.CountyFairEvents

    链接: https://ac.nowcoder.com/acm/contest/924/G 题意: Farmer John has returned to the County Fair so he ...