代码
#! /usr/bin/env python
2 # _*_ coding:utf-8 _*_
3
4 class Base1:
5
6 #私有类型成员(这只是一种规则,并不是从编译器上面限制的,
#我们依然可以用特殊语法调用这些私有成员:
#类型名称+.+_类型名称+字段名称 如:Base1._Base1__i)
7 __i = 123
8
9 a = 123 #Class Field
10
11 #初始化函数
12 def __init__(self):
13 self.b = 321 #Instance Field
14 self.x = ["a","b","e","e","n"]
15 self.test()
16 print "Base1 init ..."
17
18 def test(self):
19 print "Base1 test ..."
20
21 #加"__"私有成员(特殊方法调用: Base1()._Base1__name())
22 def __name(self):
23 print "pirvatedata..."
24
25 #静态方法
26 @staticmethod
27 def staticMethod():
28 print "staticMethod..."
29
30 #属性
31 def getI(self): return self.__b
32 def setI(self, value): self.__b = value
33 def delI(self): del self.__b
34 I = property(getI, setI, delI, "property I")
35
36 #只读属性
37 @property
38 def I(self):
39 return self.__i
40
41 #实际索引器功能
42 def __getitem__(self, key):
43 return self.x[key]
44 def __setitem__(self, key, value):
45 self.x[key] = value
46
47
48 def myTest():
49 try:
50 print "mytest..."
51 except RuntimeError, e:
52 print "[RuntimeError]", e
53 except Exception, e:
54 print "[Error]", e
55 finally:
56 print "finally"
57
58
59 #析构函数
60 def __del__(self):
61 pass
代码
#-------------------------------------------------------
63 class Base2:
64 def __init__(self):
65 print "Base2 init ..."
66
67 def test(self):
68 print "Base2 test ..."
69
70 #-------------------------------------------------------
71 class Class1(Base1, Base2):
72 def __init__(self):
73 #基类__init__/__del__需要显示调用
74 Base1.__init__(self)
75 Base2.__init__(self)
76 print "Class1 init ..."
77
78 #-------------------------------------------------------
79 if __name__ == "__main__":
80 a = Class1()
81 #继承方法的调用和基类声明顺序有关
82 a.test()