对象的魔力
创建自已对象是python非常核心的概念,事实上,python被称为面向对象语言,本章会介绍如何创建对象。以及面向对象的概念:继承、封装、多态。
- 多态: 可对不同类的对象使用同样的操作。
- 封装:对外部世界隐藏对象的工作细节。
- 继承:以普通的类为基础建立专门的类对象。
多态
多态意味着就算不知道变量所引用的对象类型是什么,还能对它进行操作,而它也会根据对象(或类)类型的不同表现出不同的行为
多态和方法
绑定到对象特性上面的函数称为方法
>>> 'abc'.count('a')
1
>>> [1,2,'a'].count('a')
1
>>>
>>> from random import choice
>>> x=choice(['hello,world',[1,2,'e','e',4]])
>>> x.count('e')
2
>>>
多态的多种形式
>>> 1+2
3
>>> 'fish'+'license'
'fishlicense'
>>> def add(x,y):
return x+y
>>> add(1,2)
3
>>> add('fish','license')
'fishlicense'
>>> def length_message(x):
print 'The length of ',repr(x),'is',len(x)
>>> length_message('Fnord')
The length of 'Fnord' is 5
>>> length_message([1,2,3])
The length of [1, 2, 3] is 3
>>>
封装
封装是对全局作用域中其他区域中隐藏多余信息的原则
>>> c = closedObject()
>>> c.setName('sir lancelot')
>>> c.getName()
‘sir lancelot’
继承
我们不想把同一段代码写好几遍,之前使用的函数避免了这种情况。但现在又有个更微妙的问题。如果已经有了一个类,又想建立一个非常类似的类,只是添加几个方法。
比如有动物类,我们又想在动物类的基础上建立鸟类、鱼类,哺乳动物类。
类
创建自己的类
_metaclass_=type #确定使用新式类
class Person:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def greet(self):
print"hello,world! I'm %s ."%self.name
--------------
>>> foo=Person()
>>> bar=Person()
>>> foo.setName ('Luke Skywalker')
>>> bar.setName('Anakin Skywalker')
>>> foo.greet ()
hello,world! I'm Luke Skywalker .
>>> bar.greet()
hello,world! I'm Anakin Skywalker .
>>>
>>> foo.name
'Luke Skywalker'
>>> bar.name='Yoda'
>>> bar.greet()
hello,world! I'm Yoda .
>>>
特性、函数和方法
self 参数事实上正是方法和函数的区别。方法将它们的第一个参数绑定到所属的实例上,因此这个参数可以不必提供。所以可以将特性绑定到一个普通函数上,这样就不会有特殊的self参数了
class Bird:
song='Squaawk'
def sing(self):
print self.song
----------------
bird=Bird()
>>> bird.sing()
Squaawk
>>> birdsong=bird.sing
>>> birdsong()
Squaawk
指定超类
子类可以扩展超类的定义。将其他类名写在class语句后的圆括号内可以指定超类:
class Filter:
def init(self):
self.blocked=[]
def filter(self,sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter):#SPAMFilter是Filter的子类
def init(self):#重写Filter超类中的方法
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','eggs','bacon','SPAM'])
['eggs', 'bacon']
>>>
调查继承
如果想要查看一个类是否是另一个的子类。可以使用内建的issubclass函数:
>>> issubclass(SPAMFilter,Filter)
True
>>> issubclass(Filter,SPAMFilter)
False
>>>
多个超类
多重继承
class Calculator:
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 is 7
>>>
接口和内省
检查方法是否存在
>>> hasattr(tc,'talk')
True
>>> hasattr(tc,'fnord')
False
>>>