Python類的結構python
class 類名: 成員變量 成員函數 class MyClass(): first = 123 def fun(self): print "I am function"
對象的屬性和方法與類中的成員變量和成員函數對應程序員
if __name__ == "__main__": myClass = MyClass() #建立類的一個實例
構造函數__init__web
class Person: def __init__(self, name, lang, website): self.name = name self.lang = lang self.website = website
子類、父類和繼承編程
# 抽象形狀類 class Shape: # 類的屬性 edge = 0 # 構造函數 def __init__(self, edge): self.edge = edge # 類的方法 def getEdge(self): return self.edge # 抽象方法 def getArea(self): pass #三角形類,繼承抽象形狀類 class Triangle(Shape): width = 0 height = 0 # 構造函數 def __init__(self, width, height): #調用父類構造函數 Shape.__init__(self, 3) self.width = width self.height = height #重寫方法 def getArea(self): return self.width * self.height / 2 #四邊形類,繼承抽象形狀類 class Rectangle(Shape): width = 0 height = 0 # 構造函數 def __init__(self, width, height): #調用父類構造函數 Shape.__init__(self, 4) self.width = width self.height = height #重寫方法 def getArea(self): return self.width * self.height triangle = Triangle(4,5); print triangle.getEdge() print triangle.getArea() rectangle = Rectangle(4,5); print rectangle.getEdge() print rectangle.getArea()
python支持多繼承,但不推薦使用數組