python学习笔记.docx
《python学习笔记.docx》由会员分享,可在线阅读,更多相关《python学习笔记.docx(20页珍藏版)》请在冰点文库上搜索。
python学习笔记
模块
几个模块相关的规则:
∙一个文件代表一个模块。
∙ 可以用importmodule导入模块,也可以用formmoduleimportmember导入模块的成员。
∙如果导入的是module,必须使用module.member进行访问;如果导入的member,可以直接访问member。
∙导入的module或member都会变成当前module的member。
b.py
1#coding=utf-8
2
3print__name__
4
5defsay_b():
6print"b"
a.py
1#coding=utf-8
2
3importb
4frombimport*
5
6print__name__
7
8defsay_a():
9print"a"
test.py
1#coding=utf-8
2
3importa
4
5print__name__
6
7a.say_a();
8a.say_b();
9a.b.say_b()
输出
1b
2a
3__main__
4a
5b
6b
异常管理
1#coding=utf-8
2
3#自定义异常
4classHappyException(Exception):
5pass
6
7#引发和捕获异常
8try:
9raiseHappyException
10except:
11print("HappyException")
12
13try:
14raiseHappyException()
15except:
16print("HappyException")
17
18#捕获多种异常
19try:
20raiseHappyException
21except(HappyException,TypeError):
22print("HappyException")
23
24#重新引发异常
25try:
26try:
27raiseHappyException
28except(HappyException,TypeError):
29raise
30except:
31print("HappyException")
32
33#访问异常实例
34try:
35raiseHappyException("都是我的错")
36except(HappyException,TypeError),e:
37print(e)
38
39#按类型捕获
40try:
41raiseHappyException
42exceptHappyException:
43print("HappyException")
44exceptTypeError:
45print("TypeError")
46
47#全面捕获
48try:
49raiseHappyException
50except:
51print("HappyException")
52
53#没有异常的else
54try:
55pass
56except:
57print("HappyException")
58else:
59print("没有异常")
60
61#总会执行的final
62try:
63pass
64except:
65print("HappyException")
66else:
67print("没有异常")
68finally:
69print("总会执行")
面向对象
先上一张图
几个规则:
1.一切都是对象,python中一切都是对象,每个对象都包含一个__class__属性以标记其所属类型。
2.每个对象(记得一切都是对象啊)都包含一个__dict__属性以存储所有属性和方法。
3.每个类型都包含一个__bases__属性以标记其父类。
4.属性和方法的访问规则:
依次搜索instance、子类、父类、父类的父类、直到object的__dict__,如果找到就返回。
5.属性和方法的设置规则:
直接设置instance.__dict__。
6.以上属性和方法访问或设置规则没有考虑“魔法方法”,下文会解释。
示例
1#coding=utf-8
2
3__metaclass__=type
4
5#类型定义
6#实例方法必的第一个参数代表类型实例,类似其他语言的this。
7classAnimal:
8name="未知"#属性定义。
9
10def__init__(self,name):
#构造方法定义。
11self.name=name
12
13defgetName(self):
#实例方法定义。
14returnself.name
15
16defsetName(self,value):
17self.name=value
18
19print(Animal.name)#未知
20print(Animal.__dict__["name"])#未知
21
22animal=Animal("狗狗")
23print(animal.name)#狗狗
24print(animal.__dict__["name"])#狗狗
25print(Animal.name)#未知
26print(Animal.__dict__["name"])#未知
27print(animal.__class__.name)#未知
28print(animal.__class__.__dict__["name"])#未知
1#类型定义中的代码会执行,是一个独立的作用域。
2classTestClass:
3print("类型定义中")#类型定义中
绑定方法和未绑定方法
1classTestClass:
2defmethod(self):
3print("测试方法")
4
5test=TestClass()
6print(TestClass.method)#
7print(test.method)#>
8
9TestClass.method(test)#测试方法
10test.method()#测试方法
绑定方法已经绑定了对象示例,调用的时刻不用也不能传入self参数了。
注:
使用对象访问实例方法为何会返回绑定方法?
这个还得等到学完“魔法方法”才能解释,内部其实是拦截对方法成员的访问,返回了一个Callable对象。
私有成员
1#私有成员
2classTestClass:
3__private_property=1
4
5def__private_method():
6pass
7
8print(TestClass.__dict__)#{'__module__':
'__main__','_TestClass__private_method':
,'_TestClass__private_property':
1
难怪访问不了了,名称已经被修改了,增加了访问的难度而已。
多重继承
1#多重继承
2classBase1:
3pass
4
5classBase2:
6pass
7
8classChild(Base2,Base1):
9pass
10
11child=Child()
12print(isinstance(child,Child))#True
13print(isinstance(child,Base2))#True
14print(isinstance(child,Base1))#True
如果继承的多个类型之间有重名的成员,左侧的基类优先级要高,上例子Base2会胜出。
接口那里去了,鸭子类型比接口更好用。
1classTestClass1:
2defsay(self):
3print("我是鸭子1")
4
5classTestClass2:
6defsay(self):
7print("我是鸭子2")
8
9defduck_say(duck):
10duck.say()
11
12duck_say(TestClass1())#我是鸭子1
13duck_say(TestClass2())#我是鸭子2
调用父类
1#调用父类
2classBase:
3defsay(self):
4print("Base")
5
6classChild(Base):
7defsay(self):
8Base.say(self)
9super(Child,self).say()
10print("Child")
11
12child=Child()
13child.say()
魔法方法
详细内容参考:
对象构造相关:
__new__、__init__、__del__。
1fromos.pathimportjoin
2
3classFileObject:
4'''Wrapperforfileobjectstomakesurethefilegetsclosedondeletion.'''
5
6def__init__(self,filepath='~',filename='sample.txt'):
7#openafilefilenameinfilepathinreadandwritemode
8self.file=open(join(filepath,filename),'r+')
9
10def__del__(self):
11self.file.close()
12delself.file
运算符重载:
所有运算符都能重载。
1classWord(str):
2'''Classforwords,definingcomparisonbasedonwordlength.'''
3
4def__new__(cls,word):
5#Notethatwehavetouse__new__.Thisisbecausestrisanimmutable
6#type,sowehavetoinitializeitearly(atcreation)
7if''inword:
8print"Valuecontainsspaces.Truncatingtofirstspace."
9word=word[:
word.index('')]#Wordisnowallcharsbeforefirstspace
10returnstr.__new__(cls,word)
11
12def__gt__(self,other):
13returnlen(self)>len(other)
14
15def__lt__(self,other):
16returnlen(self)17
18def__ge__(self,other):
19returnlen(self)>=len(other)
20
21def__le__(self,other):
22returnlen(self)<=len(other)
23
24print(Word("duan")>Word("wei"))
属性访问。
1classAccessCounter:
2'''Aclassthatcontainsavalueandimplementsanaccesscounter.
3Thecounterincrementseachtimethevalueischanged.'''
4
5def__init__(self,value):
6super(AccessCounter,self).__setattr__('counter',0)
7super(AccessCounter,self).__setattr__('value',value)
8
9def__setattr__(self,name,value):
10ifname=='value':
11super(AccessCounter,self).__setattr__('counter',self.counter+1)
12#Makethisunconditional.
13#Ifyouwanttopreventotherattributestobeset,raiseAttributeError(name)
14super(AccessCounter,self).__setattr__(name,value)
15
16def__delattr__(self,name):
17ifname=='value':
18super(AccessCounter,self).__setattr__('counter',self.counter+1)
19super(AccessCounter,self).__delattr__(name)
集合实现。
1classFunctionalList:
2'''Aclasswrappingalistwithsomeextrafunctionalmagic,likehead,
3tail,init,last,drop,andtake.'''
4
5def__init__(self,values=None):
6ifvaluesisNone:
7self.values=[]
8else:
9self.values=values
10
11def__len__(self):
12returnlen(self.values)
13
14def__getitem__(self,key):
15#ifkeyisofinvalidtypeorvalue,thelistvalueswillraisetheerror
16returnself.values[key]
17
18def__setitem__(self,key,value):
19self.values[key]=value
20
21def__delitem__(self,key):
22delself.values[key]
23
24def__iter__(self):
25returniter(self.values)
26
27def__reversed__(self):
28returnFunctionalList(reversed(self.values))
29
30defappend(self,value):
31self.values.append(value)
32defhead(self):
33#getthefirstelement
34returnself.values[0]
35deftail(self):
36#getallelementsafterthefirst
37returnself.values[1:
]
38definit(self):
39#getelementsuptothelast
40returnself.values[:
-1]
41deflast(self):
42#getlastelement
43returnself.values[-1]
44defdrop(self,n):
45#getallelementsexceptfirstn
46returnself.values[n:
]
47deftake(self,n):
48#getfirstnelements
49returnself.values[:
n]
可调用对象,像方法一样调用对象。
1classEntity:
2'''Classtorepresentanentity.Callabletoupdatetheentity'sposition.'''
3
4def__init__(self,size,x,y):
5self.x,self.y=x,y
6self.size=size
7
8def__call__(self,x,y):
9'''Changethepositionoftheentity.'''
10self.x,self.y=x,y
11print(x,y)
12
13entity=Entity(5,1,1)
14entity(2,2)
资源管理
1classCloser:
2def__enter__(self):
3returnself
4
5def__exit__(self,exception_type,exception_val,trace):
6print("清理完成")
7returnTrue;
8
9withCloser()ascloser:
10pass
对象描述符。
1classMeter(object):
2'''Descriptorforameter.'''
3
4def__init__(self,value=0.0):
5self.value=float(value)
6def__get__(self,instance,owner):
7returnself.value
8def__set__(self,instance,value):
9self.value=float(value)
10
11classFoot(object):
12'''Descriptorforafoot.'''
13
14def__get__(self,instance,owner):
15returninstance.meter*3.2808
16def__set__(self,instance,value):
17instance.meter=float(value)/3.2808
18
19classDistance(object):
20'''Classtorepresentdistanceholdingtwodescriptorsforfeetand
21meters.'''
22meter=Meter()
23foot=Foot()
Mixin(也叫掺入)
掺入模块:
playable.py
1#coding=utf-8
2
3defpaly(self):
4print("游戏中...")
掺入目标模块:
test.py
1#coding=utf-8
2
3classAnimal:
4fromplayableimportpaly
5
6animal=Animal()
7animal.paly()#游戏中...
OpenClass(打开类型,从新定义成员)
1#coding:
utf-8
2
3classTestClass:
4defmethod1(self):
5print("方法1")
6
7defmethod2(self):
8print("方法2")
9
10TestClass.method2=method2
11
12test=TestClass()
13test.method1()#方法1
14test.method2()#方法2
MetaProgramming(元编程)
1TestClass=type("TestClass",(object,),{
2"say":
lambdaself:
print("你好啊")
3})
4
5test=TestClass()
6test.say()
1defgetter(name):
2defgetterMethod(self):
3returnself.__getattribute__(name)
4returngetterMethod
5
6defsetter(name):
7defsetterMethod(self,value):
8self.__setattr__(name,value)
9returnsetterMethod
10
11classTestClass:
12getName=getter("name")
13setName=setter("name")
14
15test=TestClass()
16test.setName("段光伟")
17print(test.getName())