創建一個名為 Restaurant 的類,其方法 __init__() 設置兩個屬性:
name 和 type
1、創建一個名為 describe_restaurant() 的方法,前者打印前述兩項信息
2、創建一個名為 open_restaurant() 的方法,打印一條消息,指出餐館正在營業
3、創建一個名為 working_time ()的方法,打印一條消息,指出餐館營業歷史
4、創建一個名為 update_year() 的方法,打印一條消息,更新餐館營業時間,且更新時間要比原有時間大
5、創建一個名為 increat_years 的方法,打印一條消息,在原有時間的基礎之上增加新的營業時間
#!/usr/bin/env python # -*- coding:utf-8 -*- class Restaurant(): def __init__(self,name,type): '''初始化屬性name/type和屬性years默認值為100''' self.name=name self.type=type self.years=100 def describe_restaurant(self): '''描述餐館的名稱以及類型''' print("the restaurant'name is " + self.name.title() + " it's a " + self.type + " restaurant.") def open_restayurant(self): '''指出餐館正在營業''' print("the restaurant is working.") def working_time(self): '''指出餐館營業時間''' print("the restaurant has working " + str(self.years) + "!") def update_year(self,years): '''更新餐館營業時間,此值只能大於原有時間設置''' if years >= self.years: self.years = years else: print('you can not roll back !') def increat_years(self,time): '''從原有時間基礎之上增加新的餐館營業的時間''' if time >= 0: self.years += time else: print('請輸入不小於0的值') #調用 my_restaurant=Restaurant('HAOZAILAI','CHINESE') print(my_restaurant.name.title()) print(my_restaurant.type) my_restaurant.describe_restaurant() my_restaurant.open_restayurant() my_restaurant.working_time() '''直接訪問屬性修改屬性''' # my_restaurant.years=200 '''利用方法修改屬性''' my_restaurant.update_year(200) my_restaurant.working_time() my_restaurant.increat_years(10) my_restaurant.working_time()
結果:
Haozailai CHINESE the restaurant'name is Haozailai it's a CHINESE restaurant. the restaurant is working. the restaurant has working 100! the restaurant has working 200! the restaurant has working 210!
