python類的建立python
class Person: def setName(self, name): self.name = name def getName(self): return self.name def greet(self): print(''Helllo, world! I'm %s." % self.name)
定義時,成員函數的第一個參數爲self,至關於C++的this函數
成員變量定義時不須要單獨定義,在成員函數使用self調用便可this
定義私有變量和私有函數,只須要在前面加雙下劃線便可spa
def __inaccessible(self): print("inaccessible function")
然而Python中定義的私有類型,在外部並不是徹底不可調用,,由於在類的內部定義中私有類型是被翻譯成單下劃線加類名做爲前綴的類型,即翻譯
_類名__inaccessiblecode
這樣在外部也能夠調用。blog
類的繼承繼承
類繼承是在類定義時類名後的圓括號內指定父類(或超類)get
class Filter: def init(self): self.blocked = [] def filter(self, sequece): return [x for x in sequence if x not in selt.blocked] class SPAMFilter(Filter): def init(self): self.blocked = ['SPAM']
類中init是類的構造函數it
檢查繼承性,能夠使用內建的issubclass函數:
>>> issubclass(SPAMFilter, Filter)
True
若是要繼承多個類,就在括號裏依次添加類名