類的詳解

類的定義
class
Python中的類沒有什麼public、private、protect

構造函數、析構函數
__init__(self)
__del__(self)

類的靜態變量
class Student
  name="abc"
這東西其實就是相當於C#中的靜態變量,但這裏要注意是,初始化類的靜態變量是這樣的(DiveIntoPython中的例子)
class counter:
    count = 0                    
    def __init__(self):
      self.__class__.count += 1

實例的成員變量
class Student
  def __init__(self)
      self.name = "abc"

私有變量
class Student:
    def __init__(self):
        self.__name="abc"
很簡單就是通過__ 兩個下劃線開頭,但不是結尾的。就是私有了

私有方法
class Student:
    def __Getage(self):
        pass
和私有的變量一樣,你可以嘗試一下直接調用,編譯器會有相應的提示

強制訪問私有方法、變量
"私有"事實上這只是一種規則,我們依然可以用特殊的語法來訪問私有成員。
上面的方法,我們就可以通過_類名來訪問
aobj = Student()
aobj._Student__name
aobj._Student__Getage()

靜態方法
class Class1: 
    @staticmethod 
    def test(): 
      print "In Static method..." 

方法重載
python是不支持方法重載,但是你代碼了可以寫。Python會使用位置在最後的一個。我覺得這可能以Python存儲這些信息通過__dict__ 有關,它就是一個Dict。key是不能相同的。所以也就沒辦法出現兩個GoGo 方法調用

class Student:
    def GoGo(self,name):
        print name
    def GoGo(self):
        print "default"

調用的時候你只能使用 obj.GoGo()這個方法。

一些特殊方法

__init__(self)  構造函數
__del__ (self)  析構函數
__repr__( self)   repr()
__str__( self)    print語句 或 str()

運算符重載
__lt__( self, other)
__le__( self, other)
__eq__( self, other)
__ne__( self, other)
__gt__( self, other)
__ge__( self, other)

這東西太多了。大家還是自己看Python自帶幫助吧。

一些特殊屬性
當你定義一個類和調用類的實例時可以獲得的一些默認屬性
class Student:
    '''this test class'''
    name = 'ss'
    def __init__(self):
        self.name='bb'
    def Run(self):
        '''people Run'''
    @staticmethod 
    def RunStatic(): 
        print "In Static method..."
print Student.__dict__ #類的成員信息
print Student.__doc__  #類的說明
print Student.__name__ #類的名稱
print Student.__module__ #類所在的模塊
print Student.__bases__ #類的繼承信息
obj = Student()

print dir(obj)
print obj.__dict__ #實例的成員變量信息(不太理解Python的這個模型,爲什麼Run這個函數確不再dict中)
print obj.__doc__  #實例的說明
print obj.__module__ #實例所在的模塊
print obj.__class__ #實例所在的類名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章