面向对象
类中的属性: 域和方法
类的方法的第一个参数为self(类似于this指针),调用时无需写明
__init__方法,在类的对象被建立时,马上运行。(类似于构造函数)def __init__(slef, name):
__del__方法,(类似于析构函数)
有两种类型的 域:类的变量和对象的变量(类似于c#中静态变量),是否有self来区分两者。
python中所有类成员是公共的,方法是有效地。例外:双下划线为前缀的数据成员是私有的。
继承:
1 # Filename: inherit.py
2 class SchoolMember:
3 "'Represents any school member.'"
4 def __init__(self, name, age):
5 self.name = name
6 self.age = age
7 print '(Initialized SchoolMember: %s)' %self.name
8 def tell(self):
9 "'Tell my details.'"
10 print 'Name: %s, Age: %s' %(self.name, self.age),
11
12 class Teacher(SchoolMember):
13 "'Represents a teacher.'"
14 def __init__(self, name, age, salary):
15 SchoolMember.__init__(self, name, age)
16 self.salary = salary
17 print '(Initialized Teacher: %s)' %self.name
18 def tell(self):
19 SchoolMember.tell(self)
20 print 'Salary: %d' %self.salary
21
22 class Student(SchoolMember):
23 "'Represents a student.'"
24 def __init__(self, name, age, marks):
25 SchoolMember.__init__(self, name, age)
26 self.marks = marks
27 print '(Initialized Student: %s)' %self.name
28 def tell(self):
29 SchoolMember.tell(self)
30 print 'Marks: %d' %self.marks
31
32 t = Teacher('Mrs.Shrividya', 40, 30000)
33 s = Student('Swaroop', 22, 75)
34 print
35 members = [t, s] #a list
36 for member in members:
37 member.tell()
测试结果:
(Initialized SchoolMember: Mrs.Shrividya)
(Initialized Teacher: Mrs.Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name: Mrs.Shrividya, Age: 40 Salary: 30000
Name: Swaroop, Age: 22 Marks: 75
文件
通过file类的read、readline、write方法读写文件。读写能力依赖于打开文件时指定的模式
1 # Filename: using_file.py
2 poem = '''
3 Programming is fun
4 When the work is done
5 if you wanna make your work also fun:
6 use Python!
7 '''
8
9 f = file('poem.txt', 'w')
10 f.write(poem)
11 f.close
12 # if no mode is specified, 'r'ead mode is assumed by default
13 f = file('poem.txt')
14 while True:
15 line = f.readline()
16 if (line) == 0: # Zero length indicates EOF
17 break
18 print line,
19 f.close()
测试结果:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
储存器
python提供一个标准的模块,叫做pickle。可以存储python对象,又可以完整无缺的取出来。
cPickle用c语言实现,速度更快。
方法:dump()存入对象到文件。 load()从文件装载对象
1 # Filename: pickling.py
2 import pickle as p
3
4 # the name of the file where we will store the object
5 shoplistfile = 'shoplist.data'
6 shoplist = ['apple', 'mango', 'carrot']
7
8 # Write to the line
9 f = file(shoplistfile, 'w')
10 p.dump(shoplist, f) # dump the object to a file
11 f.close()
12 del shoplist
13 f = file(shoplistfile)
14 storedlist = p.load(f)
15 print storedlist
测试结果:
['apple', 'mango', 'carrot']
制作自定义的Exception,通常是要继承Exception类。
错误抛出:raise函数。抛出后,用except去catch并将一场对象传给x。
1 # Filename: raising.py
2 class ShortInputException(Exception):
3 '''A User-defined exception class.'''
4 def __init__(self, length, atleast):
5 Exception.__init__(self)
6 self.length = length
7 self.atleast = atleast
8
9 try:
10 s = raw_input('Enter something-->')
11 if len(s) < 3:
12 raise ShortInputException(len(s), 3)
13 except EOFError:
14 print '\nWhy did you do an EOF on me?'
15 except ShortInputException, x:
16 print 'ShortException: The input was of length %d was at least %d\
17 ' %(x.length, x.atleast)
18 else:
19 print 'No exception was raised.'
测试结果:
>>>
Enter something-->ab
ShortException: The input was of length 2 was at least 3
>>> ================================ RESTART ================================
>>>
Enter something-->hello
No exception was raised.
>>> ================================ RESTART ================================
>>>
Enter something-->
Why did you do an EOF on me?
try...finally...finally块是无论如何要执行的。
1 # Filename: finally.py
2 import time
3 try:
4 f = file('poem.txt')
5 while True:
6 line = f.readline()
7 if len(line) == 0:
8 break
9 time.sleep(2)
10 print line,
11 finally:
12 f.close()
13 print 'Cleaning up...closed the file'