Python 基礎文法(三)

來源:互聯網
上載者:User

標籤:輸出   檔案操作   post   類的方法   它的   default   變數   pre   present   

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 基礎文法(四) ----------------------------------------------

 

Python 基礎文法(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.