Python學習總結19:類(一)

    在Python中,能夠經過class關鍵字定義本身的類,經過類私有方法「__init__」進行初始化。能夠經過自定義的類對象類建立實例對象javascript

class Student(object):
    count = 0
    books = []
    def __init__(self, name, age):
        self.name = name
        self.age = age
    pass

1. 數據屬性java

    在上面的Student類中,」count」」books」」name」和」age」都被稱爲類的數據屬性,可是它們又分爲類數據屬性實例數據屬性python

Student.books.extend(["python", "javascript"])  
print "Student book list: %s" %Student.books    
# class can add class attribute after class defination
Student.hobbies = ["reading", "jogging", "swimming"]
print "Student hobby list: %s" %Student.hobbies    
print dir(Student)
 
 
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 wilber
wilber.gender = "male"
print "%s is %s" %(wilber.name, wilber.gender)   
# class instance can access class attribute
print dir(wilber)
wilber.books.append("C#")
print wilber.books

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 wilber
print dir(will)     
print will.books

     經過內建函數dir(),或者訪問類的字典屬性__dict__,這兩種方式均可以查看類有哪些屬性。app

>>> print dir(Student)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'books', 'count', 'hobbies']

    1)特殊的類屬性ssh

     對於全部的類,都有一組特殊的屬性:函數

類屬性 含義
__name__ 類的名字(字符串)
__doc__ 類的文檔字符串
__bases__ 類的全部父類組成的元組
__dict__ 類的屬性組成的字典
__module__ 類所屬的模塊
__class__ 類對象的類型

     2)屬性隱藏this

     類數據屬性屬於類自己,被全部該類的實例共享;而且,經過實例能夠去訪問/修改類屬性。可是,在經過實例中訪問類屬性的時候必定要謹慎,由於可能出現屬性」隱藏」的狀況。spa

wilber = Student("Wilber", 28)
 
print "Student.count is wilber.count: ", Student.count is wilber.count
wilber.count = 1    
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__
del wilber.count
print "Student.count is wilber.count: ", Student.count is wilber.count
 
print 
 
wilber.count += 3    
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__
 
del wilber.count
print
 
print "Student.books is wilber.books: ", Student.books is wilber.books
wilber.books = ["C#", "Python"]
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__
del wilber.books
print "Student.books is wilber.books: ", Student.books is wilber.books
 
print 
 
wilber.books.append("CSS")
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__

2. 方法code

    在一個類中,可能出現三種方法,實例方法、靜態方法和類方法。orm

    1)實例方法

    實例方法的第一個參數必須是」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()

    2)類方法
    類方法以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()

     3)靜態方法

 與實例方法和類方法不一樣,靜態方法沒有參數限制,既不須要實例參數,也不須要類參數,定義的時候使用@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()

     這三種方法的主要區別在於參數,實例方法被綁定到一個實例,只能經過實例進行調用;可是對於靜態方法和類方法,能夠經過類名和實例兩種方式進行調用。

3. 訪問控制

     在Python中,經過單下劃線」_」來實現模塊級別的私有化,通常約定以單下劃線」_」開頭的變量、函數爲模塊私有的,也就是說」from moduleName import *」將不會引入以單下劃線」_」開頭的變量、函數。

     如今有一個模塊lib.py,內容用以下,模塊中一個變量名和一個函數名分別以」_」開頭:

numA = 10
_numA = 100
 
def printNum():
    print "numA is:", numA
    print "_numA is:", _numA
 
def _printNum():
    print "numA is:", numA
print "_numA is:", _numA

     當經過下面代碼引入lib.py這個模塊後,全部的以」_」開頭的變量和函數都沒有被引入,若是訪問將會拋出異常:

from lib import *
print numA
printNum()
 
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"
    pass
 
wilber = Student("Wilber", 28)
print wilber.__address

     當經過實例wilber訪問這個屬性的時候,就會獲得一個異常,提示屬性」__address」不存在。

     其實,經過內建函數dir()就能夠看到其中的一些起因,」__address」屬性在運行時,屬性名被改成了」_Student__address」(屬性名前增長了單下劃線和類名)

>>> wilber = Student("Wilber", 28)
>>> dir(wilber)
['_Student__address', '__class__', '__delattr__', '__dict__', '__doc__', '__form
at__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '
__subclasshook__', '__weakref__', 'age', 'name']

     因此說,即便是雙下劃線,也沒有實現屬性的私有化,由於經過下面的方式仍是能夠直接訪問」__address」屬性: 

>>> wilber = Student("Wilber", 28)
>>> print wilber._Student__address
Shanghai

    雙下劃線的另外一個重要的目地是,避免子類對父類同名屬性的衝突。

class A(object):
    def __init__(self):
        self.__private()
        self.public()
 
    def __private(self):
        print 'A.__private()'
 
    def public(self):
        print 'A.public()'
 
class B(A):
    def __private(self):
        print 'B.__private()'
 
    def public(self):
        print 'B.public()'
 
b = B()

    當實例化B的時候,因爲沒有定義__init__函數,將調用父類的__init__,可是因爲雙下劃線的」混淆」效果,」self.__private()」將變成 「self._A__private()」

     「_」和」 __」的使用 更多的是一種規範/約定,不沒有真正達到限制的目的:

     「_」:以單下劃線開頭的表示的是protected類型的變量,即只能容許其自己與子類進行訪問;同時表示弱內部變量標示,如,當使用」from moduleNmae import *」時,不會將以一個下劃線開頭的對象引入。
     「__」:雙下劃線的表示的是私有類型的變量。只能是容許這個類自己進行訪問了,連子類也不能夠,這類屬性在運行時屬性名會加上單下劃線和類名。

總結

本文介紹了Python中class的一些基本點:

  • 實例數據屬性和類數據屬性的區別,以及屬性隱藏
  • 實例方法,類方法和靜態方法直接的區別
  • Python中經過」_」和」__」實現的訪問控制
相關文章
相關標籤/搜索