python物件導向案例

2021-10-03 01:55:11 字數 3354 閱讀 7295

小結:

格式化字串需要注意

傳入的引數以及返回值

oop2.py

# 需求

# 房子(house) 有 戶型、總面積 和 家具名稱列表

# 新房子沒有任何的家具

# 家具(houseitem) 有 名字 和 占地面積,其中

# 席夢思(bed) 占地 4 平公尺

# 衣櫃(chest) 占地 2 平公尺

# 餐桌(table) 占地 1.5 平公尺

# 將以上三件 家具 新增 到 房子 中

# 列印房子時,要求輸出:戶型、總面積、剩餘面積、家具名稱列表

# houseitem:name area house:area free_area house_type item_list

class

houseitem()

:def

__init__

(self,name,area)

: self.name = name

self.area = area

def__str__

(self)

:return

("%s,占地面積為%.2f"

%(self.name,self.area)

)# bed = houseitem("席夢思",4)

# print(bed)

# chest = houseitem("衣櫃",2)

# print(chest)

# table = houseitem("桌子",1.5)

# print(table)

oop2.1.py

# 需求

# 房子(house) 有 戶型、總面積 和 家具名稱列表

# 新房子沒有任何的家具

# 家具(houseitem) 有 名字 和 占地面積,其中

# 席夢思(bed) 占地 4 平公尺

# 衣櫃(chest) 占地 2 平公尺

# 餐桌(table) 占地 1.5 平公尺

# 將以上三件 家具 新增 到 房子 中

# 列印房子時,要求輸出:戶型、總面積、剩餘面積、家具名稱列表

# houseitem:name area house:area free_area house_type item_list

from oop.oop2 import houseitem

class

house()

:def

__init__

(self,house_type,area)

: self.house_type = house_type

self.area = area

self.free_area = area

self.item_list =

def__str__

(self)

:return

("戶型為:%s####總面積為:%.2f####\n剩餘面積為:%.2f####家居列表為:%s####"

%(self.house_type,self.area,self.free_area,self.item_list)

)def

add_item

(self,item)

:print

("要新增%s"

%item)

if item.area > self.free_area:

print

("剩餘空間已經不夠辣!無法新增%s"

%item.name)

return

self.free_area -= item.area

print

("新增成功,剩餘面積為:%.2f"

% self.free_area)

bed = houseitem(

"席夢思",4

)print

(bed)

chest = houseitem(

"衣櫃",2

)print

(chest)

table = houseitem(

"桌子"

,1.5

)print

(table)

house = house(

"三室一廳"

,100

)print

(house)

house.add_item(bed)

print

(house)

class

person()

:def

__init__

(self,name,weight)

: self.name = name

self.weight = weight

def__str__

(self)

:return

"名字是%s,體重是%.2f"

%(self.name,self.weight)

# pass

defrun

(self)

:"""跑步函式

"""print

("%s愛跑步,運動前體重為%.2f"

%(self.name,self.weight)

) self.weight = self.weight-

1print

("%s愛跑步,運動後體重為%.2f"

%(self.name, self.weight)

)print

("運動分割線"

+"*"*20

)print()

defeat

(self)

:"""飲食函式"""

print

("%s進食,進食前體重為%.2f"

%(self.name,self.weight)

) self.weight +=

0.5print

("%s進食,進食後體重為%.2f"

%(self.name, self.weight)

)print

("飲食分割線"

+"*"*20

)print()

xiaoming = person(

"小明"

,60.15

)print

(xiaoming)

#呼叫__str__() 輸出自定義物件的資訊

# xiaoming.name = "小明"

# xiaoming.weight = "60.15"

xiaoming.eat(

)xiaoming.run(

)

Python 物件導向 案例

a 5 print 5 10 地板除 功能類似於數學模組當中floor 向下取整操作 print 5 10 print a 10 b 25 print b 10 print b 10 print b 10 import random import math 輸入乙個三位數與程式隨機數比較大小 如果大...

Python物件導向04 物件導向封裝案例

封裝是物件導向程式設計的一大特點 物件導向程式設計的第一步 將屬性和方法封裝到乙個抽象的類中 外界使用類建立物件,然後讓物件呼叫方法物件方法的細節都被封裝在類的內部需求 小明體重75.0公斤 小明每次跑步會 0.5公斤 小明每次吃東西體重增加1公斤 class person 人類 def init ...

Python物件導向05 物件導向封裝案例 II

封裝 封裝是物件導向程式設計的一大特點 物件導向程式設計的第一步 將屬性和方法封裝到乙個抽象的類中 外界使用類建立物件,然後讓物件呼叫方法物件方法的細節都被封裝在類的內部乙個物件的屬性可以是另外乙個類建立的物件 需求 士兵許三多有一把ak47士兵可以 槍能夠發射子彈 槍裝填裝填子彈 增加子彈數量sh...