Python面向物件作業(修改優化後)
阿新 • • 發佈:2021-02-08
技術標籤:python
Python面向物件作業
1、作業1
"""
作業1
玩個特別無聊的遊戲,猜數字。
玩家輸入一個數字與
計算機隨機生成的數字作對比
當兩個值相等時,則說明使用者猜對了
注意:外部不能獲取到計算機隨機生成的值
"""
import random
class GuessNum:
def get_num(self):
n = random.randint(1, 100)
num = int(input("請輸入一個(1-100)之間的數字猜字:"))
if num == n:
print(f"恭喜你猜對了,是:{n}")
else:
while num != n:
if num > n:
print(f"數大了,應該是{n}")
num = int(input("請重新輸入:"))
else:
print(f"數小了,應該是{n}" )
num = int(input("請重新輸入:"))
if num == n:
print(f"恭喜你猜對了,是:{n}")
print("遊戲結束")
s = GuessNum()
s.get_num()
作業1優化後代碼
import random
class GuessNum(object):
def __init__(self):
self.__rand = random.randint( 1, 10)
print(self.__rand)
def guess_num(self):
num = int(input("請輸入1-10的數字:"))
while True:
if num == self.__rand:
print(f"恭喜你猜對了!他是:{self.__rand}")
break
else:
print("輸入錯誤,請從新輸入!")
num = int(input("請輸入1-10的數字:"))
n = GuessNum()
n.guess_num()
優化前程式碼不像是個類的基本方法,都可以不用類實現,優化後可以很清楚每個方法的作用
思考:輸入一個數之後,判斷這個數是在這組連續數中前一半還是後一半,每次進行對半判斷,直到找到最終結果。
2、作業2
"""
作業2
建立一個煎餅類 呼叫烹飪時長的方法累計煎餅狀態
如果煎的時間在0-3之間則狀態為生的
如果煎的時間在3-5之間則狀態為半生不熟的
如果煎的時間在5-8之間則狀態為全熟的
當時間超過8分鐘狀態焦了
並且還可以給煎餅新增作料
比如大蔥(hhh),大蒜(hhh)?,烤腸等等
"""
import time
class Cookies:
def __init__(self, minutes): # 定義初始方法
self.cookieTime = minutes
self.State_cooking = ""
def cooking_time(self): # 定義不同烹飪時間取值的方法
if self.cookieTime >= 0 and self.cookieTime < 3:
self.State_cooking = "生的"
elif self.cookieTime >= 3 and self.cookieTime < 5:
self.State_cooking = "半生不熟"
elif self.cookieTime >= 5 and self.cookieTime < 8:
self.State_cooking = "全熟"
elif self.cookieTime >= 8:
self.State_cooking = "糊了"
else:
print("時間錯誤")
return self.State_cooking
minutes = int(time.strftime('%M', time.localtime())[1]) # 呼叫分鐘的個位數
print(minutes)
c = Cookies(minutes) # 例項化Cookies
print(c.cooking_time())
還是沒搞明白怎麼加調料、肉什麼的,後期逐步完善
作業2優化後代碼:
class Cookies(object):
def __init__(self): # 定義初始方法
self.state_cooking = "生的"
self.cookieTime = 0
self.condiment = [] # 定義列表接收調味品
def __str__(self):
return f"煎餅的狀態:{self.state_cooking},煎餅的時長:{self.cookieTime}分鐘,煎餅的調味品:{self.condiment}"
def cook_condiment(self, food): # 新增調味品用self.condiment接收
self.condiment.append(food)
def cooking_time(self, cookingtime): # 定義不同烹飪時間取值的方法
self.cookieTime += cookingtime
if self.cookieTime >= 0 and self.cookieTime < 3:
self.state_cooking = "生的"
elif self.cookieTime >= 3 and self.cookieTime < 5:
self.state_cooking = "半生不熟"
elif self.cookieTime >= 5 and self.cookieTime < 8:
self.state_cooking = "全熟"
elif self.cookieTime >= 8:
self.state_cooking = "糊了"
c = Cookies() # 例項化Cookies
m = int(input("請輸入分鐘數:"))
cond = input("請加入需要的作料:")
c.cooking_time(m)
c.cook_condiment(cond)
print(c)
請輸入分鐘數:7
請加入需要的作料:牛板筋,青菜,王中王
煎餅的狀態:全熟,煎餅的時長:7分鐘,煎餅的調味品:['牛板筋,青菜,王中王']
作業2優化前,使用了時間作為烹飪時間從0-9分鐘為一個迴圈,優點不需要人工干預,每到一個時間獲取分鐘的個位數,進行判斷,適合個位數,但是2位數的分鐘並不適合,以後需要在優化。優化後代碼,直接了當,檢視烹飪多長時間可以達到什麼效果。