练习题9-1 餐馆:
1.创建一个名为Restaurant的类,其方法__init__()设置两个属性:restaurant_name和cuisine_type.创建一个名为describe_restaurant()方法和一个名为open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业.
2.根据这个类创建一个名为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("餐厅的名字:" + self.restaurant_name)
print("烹饪方法:" + self.cuisine_type)
def open_restaurant(self):
"""餐厅开业"""
print("The " + self.restaurant_name + " is open.")
restaurant = Restaurant('人间美味', '中餐') #创建餐厅
print("餐厅的名字:" + restaurant.restaurant_name) #访问属性
print("烹饪方法:" + restaurant.cuisine_type) #访问属性
restaurant.describe_restaurant() #调用方法
restaurant.open_restaurant() #调用方法
练习题9-2 三家餐馆:
根据你为完成练习题9-1而编写的类创建三个实例,并对每个实例调用方法describe_restaurant().
a_restaurant = Restaurant('餐厅a', '中餐')
b_restaurant = Restaurant('餐厅b', '西餐')
c_restaurant = Restaurant('餐厅c', '快餐')
a_restaurant.describe_restaurant()
b_restaurant.describe_restaurant()
c_restaurant.describe_restaurant()
练习题9-3 用户:
1.创建一个名为User的类,其中包含属性first_name和last_name,还有用户简介通常会存储的其他几个属性。在类User中定义一个名为describe_user()的方法,它打印用户信息摘要;再定义一个名为great_user()方法,它向用户发出个性化的问候。
2.创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class User():
"""创建用户"""
def __init__(self, first_name, last_name, where_from):
"""初始化用户信息"""
self.first_name = first_name
self.last_name = last_name
self.where_from = where_from
def describe_user(self):
"""打印用户信息"""
print("姓:" + self.first_name)
print("名:" + self.last_name)
print("来自:" + self.where_from)
def great_user(self):
"""向用户问好"""
print("你好: " + self.first_name + self.last_name +
" 欢迎你来到Python世界.")
a_user = User('张', '三', '中国')
b_user = User('李', '四', '中国')
a_user.describe_user()
a_user.great_user()
print("---------------")
b_user.describe_user()
b_user.great_user()