Python 基礎語法(三)


--------------------------------------------Python 基礎語法(二) --------------------------------------------

七、面向對象編程

  python支持面向對象編程;類和對象是面向對象編程的兩個主要方面,類創建一個新的類型,對象是這個類的實例。

  對象可以使用普通的屬於對象的變量存儲數據,屬於對象或類的變量被稱為;對象也可以使用屬於類的函數,這樣的函數稱為類的方法;域和方法可以合稱為類的屬性。

  域有兩種類型--屬於實例的或屬於類本身;它們分別被稱為實例變量和類變量。

  類使用關鍵字class創建,類的域和方法被列在一個縮進塊中。

  類的方法必須有一個額外的第一個參數,但是在調用時不為這個參數賦值,這個特殊變量指對象本身,按照慣例它的名稱是self,類似C#中的this。

class Animal:
pass #empty block

  __init__方法  在類的一個對象被創建時調用該方法;相當於c++中的構造函數。

  __del__方法  在類的對象被銷毀時調用該方法;相當於c++中的析構函數。在使用del刪除一個對象時也就調用__del__方法。

  Python中所有的類成員(包括數據成員)都是public的;只有一個例外,如果使用的數據成員以雙下划線為前綴,則為私有變量。

class Person:
Count = 0
def __init__(self, name, age):
Person.Count += 1
self.name = name
self.__age = age

p = Person("peter", 25)
p1 = Person("john", 20)

print Person.Count #2
print p.name #peter
print p.__age #AttributeError: Person instance has no attribute '__age'

  繼承:為了使用繼承,基類的名稱作為一個元組跟在類名稱的后面;python支持多重繼承。下面是一個關於繼承的例子:

 1 class SchoolMember:
2 '''Represent any school member.'''
3 def __init__(self, name, age):
4 self.name = name
5 self.age = age
6 print "Initializing a school member."
7
8 def tell(self):
9 '''Tell my details'''
10 print "Name: %s, Age: %s, " % (self.name, self.age),
11
12 class Teacher(SchoolMember):
13 '''Represent a teacher.'''
14 def __init__(self, name, age, salary):
15 SchoolMember.__init__(self, name, age)
16 self.salary = salary
17 print "Initializing a teacher"
18
19 def tell(self):
20 SchoolMember.tell(self)
21 print "Salary: %d" % self.salary
22
23 class Student(SchoolMember):
24 '''Represent a student.'''
25 def __init__(self, name, age, marks):
26 SchoolMember.__init__(self, name, age)
27 self.marks = marks
28 print "Initializing a student"
29
30 def tell(self):
31 SchoolMember.tell(self)
32 print "Marks: %d" % self.marks
33
34 print SchoolMember.__doc__
35 print Teacher.__doc__
36 print Student.__doc__
37
38 t = Teacher("Mr. Li", 30, 9000)
39 s = Student("Peter", 25, 90)
40
41 members = [t, s]
42
43 for m in members:
44 m.tell()

  程序輸出如下:

Represent any school member.
Represent a teacher.
Represent a student.
Initializing a school member.
Initializing a teacher
Initializing a school member.
Initializing a student
Name: Mr. Li, Age: 30, Salary: 9000
Name: Peter, Age: 25, Marks: 90

八、輸入/輸出

  程序與用戶的交互需要使用輸入/輸出,主要包括控制台和文件;對於控制台可以使用raw_input和print,也可使用str類。raw_input(xxx)輸入xxx然后讀取用戶的輸入並返回。

  1. 文件輸入/輸出

    可以使用file類打開一個文件,使用file的read、readline和write來恰當的讀寫文件。對文件讀寫能力取決於打開文件時使用的模式,常用模式

  有讀模式("r")、寫模式("w")、追加模式("a"),文件操作之后需要調用close方法來關閉文件。

 1 test = '''\
2 This is a program about file I/O.
3
4 Author: Peter Zhange
5 Date: 2011/12/25
6 '''
7
8 f = file("test.txt", "w") # open for writing, the file will be created if the file doesn't exist
9 f.write(test) # write text to file
10 f.close() # close the file
11
12 f = file("test.txt") # if no mode is specified, the default mode is readonly.
13
14 while True:
15 line = f.readline()
16 if len(line) == 0: # zero length indicates the EOF of the file
17 break
18 print line,
19
20 f.close()

  2. 存儲器

    python提供一個標准的模塊,成為pickle,使用它可以在一個文件中存儲任何python對象,之后可以完整的取出來,這被稱為持久地存儲對象;還有另外一個模塊成為cPickle,它的功能和pickle完全一樣,只不過它是用c寫的,要比pickle速度快(大約快1000倍)。

import cPickle

datafile = "data.data"

namelist = ["peter", "john", "king"]

f = file(datafile, "w")
cPickle.dump(namelist, f)
f.close()

del namelist

f = file(datafile)
storednamelist = cPickle.load(f)

print storednamelist
#['peter', 'john', 'king']

九、異常

  當程序中出現某些異常的狀況時,異常就發生了。python中可以使用try ... except 處理。

try:
print 1/0
except ZeroDivisionError, e:
print e
except:
print "error or exception occurred."

#integer division or modulo by zero

  可以讓try ... except 關聯上一個else,當沒有異常時則執行else。

  我們可以定義自己的異常類,需要繼承Error或Exception。

class ShortInputException(Exception):
'''A user-defined exception class'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast

try:
s = raw_input("enter someting-->")
if len(s) < 3:
raise ShortInputException(len(s), 3)
except EOFError:
print "why you input an EOF?"
except ShortInputException, ex:
print "The lenght of input is %d, was expecting at the least %d" % (ex.length, ex.atleast)
else:
print "no exception"
#The lenght of input is 1, was expecting at the least 3

  try...finally

try:
f = file("test.txt")
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print "Cleaning up..."

 

---------------------------------------------- 見續 Python 基礎語法(四) ----------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM