高階程式設計技術 課後作業九(第5周)
阿新 • • 發佈:2019-01-29
9-2 三家餐館 :建立一個名為Restaurant 的類,其方法__init__() 設定兩個屬性:restaurant_name 和cuisine_type 。建立一個名為describe_restaurant() 的方法和一個名為open_restaurant() 的方法,其中前者列印前述兩項資訊,而後者列印一條訊息,指出餐館正在營業。根據編寫的類建立三個例項,並對每個例項呼叫方法describe_restaurant() 。
class Restaurant(): def __init__(self,restaurant_name,cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print("The restaurant's name is " + self.restaurant_name,end='') print(" and it's cuisine type is " + self.cuisine_type + ".") def open_restaurant(self): print("The restaurant is open.") restaurants = [Restaurant("Lao Beijing","Chinese cuisine"), Restaurant("CoCo","French cuisine"), Restaurant("KFC","snake food"),] for restaurant in restaurants: restaurant.describe_restaurant() restaurant.open_restaurant() print()
9-3 使用者 :建立一個名為User 的類,其中包含屬性first_name 和last_name ,還有使用者簡介通常會儲存的其他幾個屬性。在類User 中定義一個名為describe_user() 的方法,它列印使用者資訊摘要;再定義一個名為greet_user() 的方法,它向用戶發出個性化的問候。
class User(): def __init__(self,first_name,last_name,**user_info): self.name = first_name.title() + " " + last_name.title(); for key,value in user_info.items(): setattr(self,key,value) def describe_user(self): for key,value in vars(self).items(): print("The user's " + key + " is " + str(value) + ".") print() users = [User('Alice','Lucy',gender='female',age=16), User('Jack','Brown',gender='male',age=23), User('Alan','Walker',gender='male',occupation='singer') ] for user in users: user.describe_user()
9-4 就餐人數 :在為完成練習9-1而編寫的程式中,新增一個名為number_served 的屬性,並將其預設值設定為0。根據這個類建立一個名為restaurant 的例項;列印有多少人在這家餐館就餐過,然後修改這個值並再次列印它。新增一個名為set_number_served() 的方法,它讓你能夠設定就餐人數。呼叫這個方法並向它傳遞一個值,然後再次列印這個值。新增一個名為increment_number_served() 的方法,它讓你能夠將就餐人數遞增。呼叫這個方法並向它傳遞一個這樣的值:你認為這家餐館每天可能接待的就餐人數。
class Restaurant(): def __init__(self,restaurant_name,cuisine_type,number_served=0): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = number_served def describe_restaurant(self): print("The restaurant's name is " + self.restaurant_name,end='') print(" and it's cuisine type is " + self.cuisine_type + ".") def open_restaurant(self): print("The restaurant is open.") def set_number_served(self,number): self.number_served = number def increment_number_served(self,number): self.number_served += number def print_number_served(self): print("There are " + str(restaurant.number_served),end=' ') print("people served in this restaurant.") restaurant = Restaurant("KFC","snake food") restaurant.print_number_served() restaurant.set_number_served(100) restaurant.print_number_served() restaurant.increment_number_served(100) restaurant.print_number_served()
9-5 嘗試登入次數 :在為完成練習9-3而編寫的User 類中,新增一個名為login_attempts 的屬性。編寫一個名為increment_login_attempts() 的方法,它將屬性login_attempts 的值加1。再編寫一個名為reset_login_attempts() 的方法,它將屬性login_attempts 的值重置為0。根據User 類建立一個例項,再呼叫方法increment_login_attempts() 多次。列印屬性login_attempts 的值,確認它被正確地遞增;然後,呼叫方法reset_login_attempts() ,並再次列印屬性login_attempts 的值,確認它被重置為0。
class User():
def __init__(self,first_name,last_name,login_attempts=0,**user_info):
self.name = first_name.title() + " " + last_name.title();
self.login_attempts = login_attempts
for key,value in user_info.items():
setattr(self,key,value)
def describe_user(self):
for key,value in vars(self).items():
print("The user's " + key + " is " + str(value) + ".")
print()
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
user = User('Alice','Lucy',gender='female',age=16)
user.increment_login_attempts()
user.increment_login_attempts()
user.increment_login_attempts()
print("After logined 3 times, the login attemps is " + str(user.login_attempts) + '.')
user.reset_login_attempts()
print("After reseted, the login attemps is " + str(user.login_attempts) + '.')
9-6 冰淇淋小店 :冰淇淋小店是一種特殊的餐館。編寫一個名為IceCreamStand 的類,讓它繼承你為完成練習9-1或練習9-4而編寫的Restaurant 類。這兩個版本的Restaurant 類都可以,挑選你更喜歡的那個即可。新增一個名為flavors 的屬性,用於儲存一個由各種口味的冰淇淋組成的列表。編寫一個顯示這些冰淇淋的方法。建立一個IceCreamStand 例項,並呼叫這個方法。
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("The restaurant's name is " + self.restaurant_name,end='')
print(" and it's cuisine type is " + self.cuisine_type + ".")
def open_restaurant(self):
print("The restaurant is open.")
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type,*flavors):
super().__init__(restaurant_name,cuisine_type)
self.flavors = flavors
def print_icecream(self):
print("\n--- flavor ice cream ---")
for flavor in self.flavors:
print(flavor)
shop = IceCreamStand("MacDonald","ice cream","chocolate","Matcha","strawberry")
shop.print_icecream()
9-7 管理員 :管理員是一種特殊的使用者。編寫一個名為Admin 的類,讓它繼承你為完成練習9-3或練習9-5而編寫的User 類。新增一個名為privileges 的屬性,用於儲存一個由字串(如"can add post" 、"can delete post" 、"can ban user" 等)組成的列表。編寫一個名為show_privileges() 的方法,它顯示管理員的許可權。建立一個Admin 例項,並呼叫這個方法。
class User():
def __init__(self,first_name,last_name,**user_info):
self.name = first_name.title() + " " + last_name.title();
for key,value in user_info.items():
setattr(self,key,value)
def describe_user(self):
for key,value in vars(self).items():
print("The user's " + key + " is " + str(value) + ".")
print()
class Admin(User):
def __init__(self,first_name,last_name,*privileges,**user_info):
super().__init__(first_name,last_name,**user_info)
self.privileges = privileges
def show_privileges(self):
print("The Administer," + self.name + "'s privileges are:")
for privilege in self.privileges:
if self.gender == 'male':
print("He ",end='')
else:
print("She ",end='')
print(privilege)
admin = Admin("Lily","James","can add post","can delete post","can ban user",gender='female')
admin.show_privileges()
9-8 許可權 :編寫一個名為Privileges 的類,它只有一個屬性——privileges ,其中儲存了練習9-7 所說的字串列表。將方法show_privileges() 移到這個類中。在Admin 類中,將一個Privileges 例項用作其屬性。建立一個Admin 例項,並使用方法show_privileges() 來顯示其許可權。
class Privileges():
def __init__(self,privileges):
self.privileges = privileges
def show_privileges(self):
print("The Administer's privileges are:")
for privilege in self.privileges:
print(privilege)
class User():
def __init__(self,first_name,last_name,**user_info):
self.name = first_name.title() + " " + last_name.title();
for key,value in user_info.items():
setattr(self,key,value)
def describe_user(self):
for key,value in vars(self).items():
print("The user's " + key + " is " + str(value) + ".")
print()
class Admin(User):
def __init__(self,first_name,last_name,*privileges,**user_info):
super().__init__(first_name,last_name,**user_info)
self.privileges = Privileges(privileges)
admin = Admin("Lily","James","can add post","can delete post","can ban user",gender='female')
admin.privileges.show_privileges()
9-9 電瓶升級 :在本節最後一個electric_car.py版本中,給Battery 類新增一個名為upgrade_battery() 的方法。這個方法檢查電瓶容量,如果它不是85,就將它設定為85。建立一輛電瓶容量為預設值的電動汽車,呼叫方法get_range() ,然後對電瓶進行升級,並再次呼叫get_range() 。你會看到這輛汽車的續航里程增加了。
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
if self.battery_size != 85:
range = 85
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
print("After upgraded,",end='')
my_tesla.battery.get_range()