Python的OO思想
想当年大二的时候,在学校学习Java,最牛逼的OO思想,用了3页纸就讲完了,还是清华大学出版社的呢。
后来全凭自己啃视频,啃代码才搞懂什么叫做OO。
现在学习Python,就用自己的方式,好好学习一次:
OO的基本,是封装,继承,多态。
首先是继承:
定义一个类:
Python代码
[*]class Bird(object):
[*] have_feather = True
[*] way_of_reproduction= 'egg'
调用这个类:
Python代码
[*]summer = Bird()
[*]print summer.way_of_reproduction
与Java不同是,Python是不需要new来实例化类的。
同样,Python的类下面是可以定方法的:
Python代码
[*]class Bird(object):
[*] have_feather = True
[*] way_of_reproduction = 'egg'
[*]
[*] def say(self, word='hi hi'):
[*] print 'i say :' + word
注意一点,所有类的函数,必须至少带有一个参数,这个参数必须是self。
类以外的函数没有这一个限制。
Python代码
[*]chk = Chicken()
[*]print chk.have_feather
[*]print chk.sat('hello')
__init__()方法
__init__()是一个特殊方法(special method)。Python里会有一些特殊方法,Python会以特别的方式处理它们。特殊方法的名字的特点是前后都有两个下划线。
__init__()方法的特殊在于,如果你在类中定义了这个方法,一旦你根据这个类建立对象,Python就会自动调用这个方法(这个过程也叫初始化)。
如:
Python代码
[*]class happyBird(Bird):
[*] def __init__(self,more_words):
[*] print 'We are happy birds.',more_words
[*]
[*]hb = happyBird('Happy,Happy!')
父类方法的重载:
Python代码
[*]class Hello(object):
[*] name = 'hello'
[*]
[*] def __init__(self):
[*] self.name='my name is hello'
[*]
[*] #类中的参数必须带有self参数
[*] def sayhi(self):
[*] print 'hi you'
[*]
[*]class World(Hello):
[*] def __init__(self):
[*] #这里访问的是父类初始化的变量名
[*] print 'before:',Hello.name
[*] super(World,self).__init__()
[*] #由于调用了父类的初始化构造函数,继承了父类的变量的改变
[*] print 'after:',self.name
[*]
[*] #近似于方法重载
[*] def sayhi(self,word='baby'):
[*] #调用父类sayhi方法
[*] super(World,self).sayhi()
[*] print 'hi '+word
[*]
[*] def sayWorld(self):
[*] print 'hi,hello world'
[*]
[*]if __name__ == '__main__':
[*] c = World()
[*] c.sayhi()
[*] c.sayWorld()
另外,python是允许多继承的,但是这个是个非常危险的操作,建议不要随便使用。
关于Python的多态,就像JavaScript一样,直接访问对象的属性,不需要使用接口,没有类型转换。
对于类型的判断,有抓们的type()函数,和isinstance()函数判断是否某个函数的子类。
Python代码
[*]isinstance(object, classinfo)
[*]判断实例是否是这个类或者object是变量
[*]
[*]classinfo 是类型(tuple,dict,int,float)
[*]判断变量是否是这个类型
[*]
[*]class objA:
[*]pass
[*]
[*]A = objA()
[*]B = 'a','v'
[*]C = 'a string'
[*]
[*]print isinstance(A, objA)
[*]print isinstance(B, tuple)
[*]print isinstance(C, basestring)
[*]输出结果:
[*]True
[*]True
[*]True
页:
[1]