Python是面向对象的编程语言,面向对象的基本单元是类
类的声明:
1 class class_name(): 2 pass
测试如下:
In [1]: class c(): ...: pass ...: In [2]: a=c() In [3]: a Out[3]: <__main__.c instance at 0x07500A30>
类的继承:
1 In [4]: class base(): 2 ...: def f(self): 3 ...: print 'base' 4 ...: 5 6 In [5]: class sub(base): 7 ...: pass 8 ...: 9 10 In [6]: x=sub() 11 12 In [7]: x.f 13 Out[7]: <bound method sub.f of <__main__.sub instance at 0x074FD7D8>> 14 15 In [8]: x.f() 16 base
成员变量,在初始化函数__init__中对成员变量赋值即可,__init__函数相当于C++及Java中的构造函数
例如:
1 In [9]: class c(): 2 ...: def __init__(self,name,age): 3 ...: self._name=name 4 ...: self._age=age 5 ...: def printinfo(self): 6 ...: print self._name,self._age 7 ...: 8 9 In [10]: x=c('P','10') 10 11 In [11]: x.printinfo() 12 P 10
实例属性
1 class d(): 2 def __init__(self): 3 self._name='a' 4 self._age=10 5 def printinfo(self): 6 print self._name,self._age 7 8 #============================================================================== 9 # 第一种方式 10 #============================================================================== 11 def get_name(self): 12 return self._name 13 14 def set_name(self,value): 15 self._name=value 16 17 name=property(fget=get_name,fset=set_name) 18 19 #============================================================================== 20 # 第一种方式 21 #============================================================================== 22 @property 23 def age(self): 24 return self._age 25 26 @age.setter 27 def age(self,value): 28 self._age=value 29 30
测试如下:
1 In [16]: x=d() 2 3 In [17]: x.printinfo() 4 a 10 5 6 In [18]: x.name 7 Out[18]: 'a' 8 9 In [19]: x.age 10 Out[19]: 10 11 12 In [20]: x.name='b' 13 14 In [21]: x.name 15 Out[21]: 'b' 16 17 In [22]: x.age=9 18 19 In [23]: x.age 20 Out[23]: 9
虚函数性质,同名覆盖
1 class e(): 2 def f(self): 3 print 'base' 4 5 class f(e): 6 def f(self): 7 print 'son' 8 9 class g(e): 10 pass 11 12 class h(): 13 def f(self,e): 14 e.f() 15 16 a=e() 17 a.f() 18 b=f() 19 b.f() 20 c=g() 21 c.f() 22 x=h() 23 x.f(a) 24 x.f(b) 25 x.f(c)
测试结果
1 base 2 son 3 base 4 base 5 son 6 base