更加抽像
对象的魔力
多态 polymorphism
Def (x,y):
Return x+y
Add(1,2)
3
封装 encapsulation
继承 inheritance
类和类型
创建自已的类
>>>class Person:
#使用 self绑定方法
def setName(self,name):
self.name=name
def getName(self):
return self.name
def greet(self):
print('hello,world! I am %s .' % self.name)
>>>foo=Person()
>>>bar=Person()
>>>foo.setName('retacn yue')
>>>bar.setName('three yue')
>>>foo.name
'retacn yue'
>>>bar.name
'three yue'
>>>foo.getName()
'retacn yue'
>>>bar.getName()
'three yue’
>>>foo.greet()
hello,world! Iam retacn yue .
>>>bar.greet()
hello,world! Iam three yue .
特性函数和方法
>>>class Bird:
song='qwuaawk!'
def sing(self):
print (self.song)
>>>bird=Bird()
>>>bird.sing()
qwuaawk!
>>>birdsong=bird.sing
>>>birdsong()
qwuaawk!
私有方法
>>>class Secretive:
def __inaccessible(self):
print('but you cant not seeme...')
def accessible(self):
print('the seccret message is:')
self.__inaccessible()
>>>s=Secretive()
>>>
>>>s.__inaccessible()
Traceback (mostrecent call last):
File "<pyshell#142>", line 1,in <module>
s.__inaccessible()
AttributeError:'Secretive' object has no attribute '__inaccessible'
>>>s.accessible()
the seccretmessage is:
but you cant notsee me...
注:实际上还参在类外访问这些方法
#3.0不能访问
s._Secretive__inaccessible
<bound methodSecretive.__inaccessible of <__main__.Secretive object at 0x029B6B10>>
类的命名空间
>>>class MemberCounter:
members=0
def init(self):
MemberCounter.members+=1
>>>m1=MemberCounter()
>>>m1.init()
>>>MemberCounter.members
1
>>>m2=MemberCounter()
>>> m2.init()
>>>MemberCounter.members
2
指定超类
>>> class Filter:
definit(self):
self.blocked=[]
deffilter(self,sequence):
return[x for x in sequence if x not in self.blocked]
>>> classSPAMFilter(Filter):#filter的子类
definit(self):#重写filter超类中的init方法
self.blocked=['SPAM']
>>> f=Filter()
>>> f.init()
>>> f.filter([1,2,3])
[1, 2, 3]
>>> s=SPAMFilter()
>>> s.init()
>>>s.filter(['SPAM','SPAM','SPAM','SPAM','egg','bacon','SPAM','SPAM'])
['egg', 'bacon']
检查继承
>>>issubclass(SPAMFilter,Filter)
True
>>>issubclass(Filter,SPAMFilter)
False
也可以使用特殊属性__bases__
>>>SPAMFilter.__bases__
(<class'__main__.Filter'>,)
>>>Filter.__bases__
(<class'object'>,)
多个超类
先继承类中的方法会重写后继承类中的方法
这一点与c++有点类似,多重继承
Java是单继承,接口可以实现多重继承
>>> classCalculator:
def calculate(self,expression):
self.value=eval(expression)
>>>class Talker:
def talk(self):
print('Hi! My value is ',self.value)
>>>class TalkingCalculator(Calculator,Talker):
pass
>>>tc=TalkingCalculator()
>>> tc.calculate('1+2*3')
>>>tc.talk()
Hi! My value is7
接口和内省
#检查方法是否存在
>>>hasattr(tc,'talk')
True
>>>hasattr(tc,'test')
False
#检查方法是否可以调用
>>>callable(getattr(tc,'talk',None))
True
>>>callable(getattr(tc,'test',None))
False
#3.0中可以使用以下方法
>>>hasattr(getattr(tc,'test',None),'__call__')
False
>>>hasattr(getattr(tc,'talk',None),'__call__')
True