Python中的類(上)
在Python中,可以通過class關鍵字定義自己的類,然後通過自訂的類對象類建立執行個體對象。
例如,下面建立了一個Student的類,並且實現了這個類的初始化函數"__init__":
class Student(object): count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age pass
接下來就通過上面的Student類來看看Python中類的相關內容。 資料屬性
在上面的Student類中,"count""books""name"和"age"都被稱為類的資料屬性,但是它們又分為類資料屬性和執行個體資料屬性。 類資料屬性和執行個體資料屬性
首先看一段代碼,代碼中分別展示了對類資料屬性和執行個體資料屬性的訪問:
Student.books.extend(["python", "javascript"]) print "Student book list: %s" %Student.books # class can add class attribute after class definationStudent.hobbies = ["reading", "jogging", "swimming"]print "Student hobby list: %s" %Student.hobbies print dir(Student)print wilber = Student("Wilber", 28) print "%s is %d years old" %(wilber.name, wilber.age) # class instance can add new attribute # "gender" is the instance attribute only belongs to wilberwilber.gender = "male"print "%s is %s" %(wilber.name, wilber.gender) # class instance can access class attributeprint dir(wilber)wilber.books.append("C#")print wilber.booksprint will = Student("Will", 27) print "%s is %d years old" %(will.name, will.age) # will shares the same class attribute with wilber# will don't have the "gender" attribute that belongs to wilberprint dir(will) print will.books
通過內建函數dir(),或者訪問類的字典屬性__dict__,這兩種方式都可以查看類有哪些屬性,代碼的輸出為:
對於類資料屬性和執行個體資料屬性,可以總結為: 類資料屬性屬於類本身,可以通過類名進行訪問/修改 類資料屬性也可以被類的所有執行個體訪問/修改 在類定義之後,可以通過類名動態添加類資料屬性,新增的類屬性也被類和所有執行個體共有 執行個體資料屬性只能通過執行個體訪問 在執行個體產生後,還可以動態添加執行個體資料屬性,但是這些執行個體資料屬性只屬於該執行個體 特殊的類屬性
對於所有的類,都有一組特殊的屬性:
類屬性 |
含義 |
__name__ |
類的名字(字串) |
__doc__ |
類的文檔字串 |
__bases__ |
類的所有父類組成的元組 |
__dict__ |
類的屬性群組成的字典 |
__module__ |
類所屬的模組 |
__class__ |
類對象的類型 |
通過這些屬性,可以得到 Student類的一些資訊:
class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age pass print Student.__name__print Student.__doc__print Student.__bases__print Student.__dict__print Student.__module__print Student.__class
代碼輸出為:
屬性隱藏
從上面的介紹瞭解到,類資料屬性屬於類本身,被所有該類的執行個體共用;並且,通過執行個體可以去訪問/修改類屬性。但是,在通過執行個體中訪問類屬性的時候一定要謹慎,因為可能出現屬性"隱藏"的情況。
繼續使用上面的Student類,來看看屬性隱藏:
wilber = Student("Wilber", 28)print "Student.count is wilber.count: ", Student.count is wilber.countwilber.count = 1 print "Student.count is wilber.count: ", Student.count is wilber.countprint Student.__dict__print wilber.__dict__del wilber.countprint "Student.count is wilber.count: ", Student.count is wilber.countprint wilber.count += 3 print "Student.count is wilber.count: ", Student.count is wilber.countprint Student.__dict__print wilber.__dict__del wilber.countprintprint "Student.books is wilber.books: ", Student.books is wilber.bookswilber.books = ["C#", "Python"]print "Student.books is wilber.books: ", Student.books is wilber.booksprint Student.__dict__print wilber.__dict__del wilber.booksprint "Student.books is wilber.books: ", Student.books is wilber.booksprint wilber.books.append("CSS")print "Student.books is wilber.books: ", Student.books is wilber.booksprint Student.__dict__print wilber.__dict__
代碼的輸出為:
分析一下上面代碼的輸出: 對於不可變類型的類屬性Student.count,可以通過執行個體wilber進行訪問,並且"Student.count is wilber.count" 當通過執行個體賦值/修改count屬性的時候,都將為執行個體wilber建立一個count執行個體屬性,這時,"Student.count is not wilber.count" 當通過"del wilber.count"語句刪除執行個體的count屬性後,再次成為 "Student.count is wilber.count"
同樣對於可變類型的類屬性Student.books,可以通過執行個體wilber進行訪問,並且"Student. books is wilber. books" 當通過執行個體賦值books屬性的時候,都將為執行個體wilber建立一個books執行個體屬性,這時,"Student. Books is not wilber. books" 當通過"del wilber. books"語句刪除執行個體的books屬性後,再次成為"Student. books is wilber. books" 當通過執行個體修改books屬性的時候,將修改wilber.books指向的記憶體位址(即Student.books),此時,"Student. Books is wilber. books"
注意,雖然通過執行個體可以訪問類屬性,但是,不建議這麼做,最好還是通過類名來訪問類屬性,從而避免屬性隱藏帶來的不必要麻煩。 方法
在一個類中,可能出現三種方法,執行個體方法、靜態方法和類方法,下面來看看三種方法的不同。 執行個體方法
執行個體方法的第一個參數必須是"self","self"類似於C++中的"this"。
執行個體方法只能通過類執行個體進行調用,這時候"self"就代表這個類執行個體本身。通過"self"可以直接存取執行個體的屬性。
class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age def printInstanceInfo(self): print "%s is %d years old" %(self.name, self.age) pass wilber = Student("Wilber", 28)wilber.printInstanceInfo()
類方法
類方法以cls作為第一個參數,cls表示類本身,定義時使用@classmethod裝飾器。通過cls可以訪問類的相關屬性。
class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age @classmethod def printClassInfo(cls): print cls.__name__ print dir(cls) pass Student.printClassInfo() wilber = Student("Wilber", 28)wilber.printClassInfo()
代碼的輸出為,從這段代碼可以看到,類方法可以通過類名訪問,也可以通過執行個體訪問。
靜態方法
與執行個體方法和類方法不同,靜態方法沒有參數限制,既不需要執行個體參數,也不需要類參數,定義的時候使用@staticmethod裝飾器。
同類方法一樣,靜態法可以通過類名訪問,也可以通過執行個體訪問。
class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age @staticmethod def printClassAttr(): print Student.count print Student.books pass Student.printClassAttr() wilber = Student("Wilber", 28)wilber.printClassAttr()
這三種方法的主要區別在於參數,執行個體方法被綁定到一個執行個體,只能通過執行個體進行調用;但是對於靜態方法和類方法,可以通過類名和執行個體兩種方式進行調用。 存取控制
Python中沒有存取控制的關鍵字,例如private、protected等等。但是,在Python編碼中,有一些約定來進行存取控制。 單底線"_"
在Python中,通過單底線"_"來實現模組層級別的私人化,一般約定以單底線"_"開頭的變數、函數為模組私人的,也就是說"from moduleName import *"將不會引入以單底線"_"開頭的變數、函數。
現在有一個模組lib.py,內容用如下,模組中一個變數名和一個函數名分別以"_"開頭:
numA = 10_numA = 100def printNum(): print "numA is:", numA print "_numA is:", _numA def _printNum(): print "numA is:", numAprint "_numA is:", _numA
當通過下面代碼引入lib.py這個模組後,所有的以"_"開頭的變數和函數都沒有被引入,如果訪問將會拋出異常:
from lib import *print numAprintNum()print _numA#print _printNum()
雙底線"__"
對於Python中的類屬性,可以通過雙底線"__"來實現一定程度的私人化,因為雙底線開頭的屬性在運行時會被"混淆"(mangling)。
在Student類中,加入了一個"__address"屬性:
class Student(object): def __init__(self, name, age): self.name = name self.age = age self.__address = "Shanghai" passwilber = Student("Wilber", 28)print wilber.__address
當通過執行個體wilber訪問這個屬性的時候,就會得到一個異常,提示屬性"__address"不存在。
其實,通過內建函數dir()就可以看到其中的一些原由,"__address"屬性在運行時,屬性名稱被改為了"_Student__address"(屬性名稱前增加了單底線和類名)
>>> wilber = Student("Wilber", 28)>>> dir(wilber)['_Student__address', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']>>>
所以說,即使是雙底線,也沒有實現屬性的私人化,因為通過下面的方式還是可以直接存取"__address"屬性:
>>> wilber = Student("Wilber", 28)>>> print wilber._Student__addressShanghai>>>
雙底線的另一個重要的目地是,避免子類對父類同名屬性的衝突。
看下面一個例子: