python小練習--屬性
阿新 • • 發佈:2017-06-04
class 開頭 類方法 文字 沒有 __init__ 計算 div 技術分享
箭頭這個作業:
1 class Box:#定義一個類名為Box,類名後不必有括號,類包含類屬性和類方法,這個類沒有定義類屬性 2 ‘‘‘這是一個計算體積的類‘‘‘#這是這個類的__doc__屬性,執行類後就可以在交互界面輸入Box.__doc__查看這行說明文字了 3 def __init__(self):#這是類的構造函數,當實例化Box後會自動調用這個__init__方法 4 self.length=0.0 #這是實例屬性,在類內訪問用self.length,在類外訪問用 實例名.length 5 self.width=0.0 6self.height=0.0 7 self.__valum=0.0#雙下換線開頭的變量表示私有變量,所以他為私有實例屬性,只能在類內訪問到 8 def computevalum(self):#定義了一個類方法。 9 self.__valum=self.length*self.width*self.height 10 print(‘長度=‘,self.length,‘寬度=‘,self.width,‘高度=‘,self.height,‘valum=‘,self.__valum) 11 computa=Box() #實例化Box類12 computa.length=1 13 computa.width=2 14 computa.height=3 15 computa.computevalum() 16 17 computb=Box()#實例化Box類 18 computb.length=2 19 computb.width=2 20 computb.height=3 21 computb.computevalum()
我只實例化了兩次。
結果:
python小練習--屬性