第九章
练习题
9-1 餐馆
创建一个名为Restaurant的类,其方法__init__()设置两个属性:restaurant_name和cuisine_type。创建一个名为describe_restaurant()的方法和一个名为open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。根据这个类创建一个名为restaurant的实例,分别打印其两个属性,再调用前述两个方法。
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self):
print("This is "+self.name.title()+"and it's a "+self.type+" restaurant.")
def open_restaurant(self):
print("The restauarnt is open now")
restaunrant=Restaurant('KingLong','Chinese')
print("The name of the restaurant is "+restaunrant.name.title())
print("It's a "+restaunrant.type+" restaurant.")
restaunrant.describe_restaurant()
restaunrant.open_restaurant()
9-2 三家餐馆
根据你为完成练习9-1而编写的类创建三个实例,并对每个实例调用方法describe_restaurant()。
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self):
print("This is "+self.name.title()+"and it's a "+self.type+" restaurant.")
def open_restaurant(self):
print("The restauarnt is open now")
restaunrant1=Restaurant('KingLong','Chinese')
restaunrant2=Restaurant('Hitomi','Japanese')
restaunrant3=Restaurant('KFC','fast food')
restaunrant1.describe_restaurant()
restaunrant2.describe_restaurant()
restaunrant3.describe_restaurant()
9-3 用户
创建一个名为User的类,其中包含属性first_name和last_name,还有用户简介通常会存储的其他几个属性。在类User中定义一个名为describe_user()的方法,它打印用户信息摘要;再定义一个名为greet_user()的方法,它向用户发出个性化的问候。创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class User():
def __init__(self,first_name,last_name,age,gender):
self.first=first_name
self.last=last_name
self.age=str(age)
self.gender=gender
def describe_user(self):
print(self.last.title()+" "+self.first+" is a "+self.gender+".")
print("He's "+self.age+" years old.")
def greet_user(self):
print("Hello,"+self.first)
seung_woo=User('seungwoo','han',27,'man')
seung_sik=User('seungsik','kang',26,'man')
seung_woo.greet_user()
seung_woo.describe_user()
seung_sik.greet_user()
seung_sik.describe_user()
9-4 就餐人数
在为完成练习9-1而编写的程序中,添加一个名为number_served的属性,并将其默认值设置为0。根据这个类创建一个名为restaurant的实例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。
添加一个名为set_nu