9-1 餐馆:创建一个名为 Restaurant 的类,其方法__init__()设置两个属性:restaurant_name 和 cuisine_type。创建一个名为 describe_restaurant()的方法和一个名为 open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。
根据这个类创建一个名为 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)
print("The restaurant's cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name + " is open.")
restaurant = Restaurant('KFC','fast food')
print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
运行结果:
KFC
fast food
The restaurant's name is KFC
The restaurant's cuisine type is fast food
KFC is open.
9-2 三家餐馆:根据你为完成练习 9-1 而编写的类创建三个实例,并对每个实例调用方法 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)
print("The restaurant's cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name + " is open.")
restaurant1 = Restaurant('KFC','fast food')
restaurant2 = Restaurant('McDonalds','fast food')
restaurant3 = Restaurant('Beijing Roast Duck','Chinese food')
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
运行结果:
The restaurant's name is KFC
The restaurant's cuisine type is fast food
The restaurant's name is McDonalds
The restaurant's cuisine type is fast food
The restaurant's name is Beijing Roast Duck
The restaurant's cuisine type is Chinese food
9-3 用户:创建一个名为 User 的类,其中包含属性 first_name 和 last_name,还有用户简介通常会存储的其他几个属性。在类 User 中定义一个名为 describe_user()的方法,它打印用户信息摘要;再定义一个名为 greet_user()的方法,它向用户发出个性化的问候。
创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class User():
def __init__(self,first_name,last_name,country):
self.first_name = first_name
self.last_name = last_name
self.country = country
def describe_user(self):
print("The user's name is " + self.first_name + self.last_name )
print("comes from " + self.country)
def greet_user(self):
print("Hello," + self.first_name + self.last_name)
user1 = User('Michael','Jordan','USA')
user2 = User('Allen','Iverson','USA')
user1.describe_user()
user1.greet_user()
user2.describe_user()
user2.greet_user()
运行结果:
The user's name is MichaelJordan
comes from USA
Hello,MichaelJordan
The user's name is AllenIverson
comes from USA
Hello,AllenIverson
9-4 就餐人数:在为完成练习 9-1 而编写的程序中,添加一个名为 number_served的属性,并将其默认值设置为 0。根据这个类创建一个名为 restaurant 的实例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。
添加一个名为 set_number_served()的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。
添加一个名为 increment_number_served()的方法,它让你能够将就餐人数递增。
调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就餐人数。
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The restaurant's name is " + self.restaurant_name)
print("The restaurant's cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name + " is open.")
def set_number_served(self,number_served):
self.number_served = number_served
def increment_number_served(self,additional_served):
self.number_served += additional_served
restaurant = Restaurant('KFC', 'fast food')
restaurant.describe_restaurant()
print("\nNumber served: " + str(restaurant.number_served))
restaurant.number_served = 200
print("Number served: " + str(restaurant.number_served))
restaurant.set_number_served(1000)
print("Number served: " + str(restaurant.number_served))
restaurant.increment_number_served(500)
print("Number served: " + str(restaurant.number_served))
运行结果:
The restaurant's name is KFC
The restaurant's cuisine type is fast food
Number served: 0
Number served: 200
Number served: 1000
Number served: 1500
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,country):
self.first_name = first_name
self.last_name = last_name
self.country = country
self.login_attempts = 0
def describe_user(self):
print("The user's name is " + self.first_name + self.last_name)
print("comes from " + self.country)
def greet_user(self):
print("Hello," + self.first_name + self.last_name)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
user1 = User('Michael','Jordan','USA')
print("loging...")
user1.increment_login_attempts()
print("loging...")
user1.increment_login_attempts()
print("loging...")
user1.increment_login_attempts()
print("Login attempts: " + str(user1.login_attempts))
print("resetting login attempts...")
user1.reset_login_attempts()
print("Login attempts: " + str(user1.login_attempts))
运行结果:
loging...
loging...
loging...
Login attempts: 3
resetting login attempts...
Login attempts: 0
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)
print("The restaurant's cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is opening")
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors = []
def show_flavors(self):
for flavor in self.flavors:
print("This is a " + flavor + " flavored ice cream.")
iceCreamStand = IceCreamStand('KFC','ice cream')
iceCreamStand.flavors = ['vanilla','strawberry']
iceCreamStand.describe_restaurant()
iceCreamStand.show_flavors()
运行结果:
The restaurant's name is KFC
The restaurant's cuisine type is ice cream
This is a vanilla flavored ice cream.
This is a strawberry flavored ice cream.
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,country):
self.first_name = first_name
self.last_name = last_name
self.country = country
def describe_user(self):
print("The user's name is " + self.first_name + self.last_name )
print("comes from " + self.country)
def greet_user(self):
print("Hello," + self.first_name + self.last_name)
class Admin(User):
def __init__(self,first_name,last_name,country):
super().__init__(first_name,last_name,country)
self.privileges = []
def show_privileges(self):
for privilege in self.privileges:
print("Admin" + privilege)
admin = Admin('Michael','Jordan','USA')
admin.privileges = [' can add post',' can delete post',' can ban user']
admin.show_privileges()
运行结果:
Admin can add post
Admin can delete post
Admin can ban user
9-8 权限:编写一个名为 Privileges 的类,它只有一个属性——privileges,其中存储了练习 9-7 所说的字符串列表。将方法 show_privileges()移到这个类中。在 Admin类中,将一个 Privileges 实例用作其属性。创建一个 Admin 实例,并使用方法show_privileges()来显示其权限。
class User():
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print("The user's name is " + self.first_name + self.last_name)
def greet_user(self):
print("Hello," + self.first_name + self.last_name)
class Admin(User):
def __init__(self,first_name,last_name):
super().__init__(first_name,last_name)
self.privileges = Privileges()
class Privileges():
def __init__(self,privileges=[]):
self.privileges = privileges
def show_privileges(self):
for privilege in self.privileges:
print("Admin" + privilege)
admin = Admin('Michael','Jordan')
admin.privileges.privileges = [' can add post',' can delete post',' can ban user']
admin.privileges.show_privileges()
运行结果:
Admin can add post
Admin can delete post
Admin can ban user
9-9 电瓶升级:在本节最后一个electric_car.py版本中,给Battery类添加一个名为upgrade_battery()的方法。这个方法检查电瓶容量,如果它不是85,就将它设置为85。创建一辆电瓶容量为默认值的电动车,调用方法get_range(),然后对电瓶进行升级,并再次调用get_range()。你会看到这辆汽车的续航里程增加了。
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size
def descriptive_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:
self.battery_size = 85
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s',2016)
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
运行结果:
This car can go approximately 240 miles on a full charge.
This car can go approximately 270 miles on a full charge.
9-10 导入 Restaurant 类:将最新的 Restaurant 类存储在一个模块中。在另一个文件中,导入 Restaurant 类,创建一个 Restaurant 实例,并调用 Restaurant 的一个方法,以确认 import 语句正确无误。
from restaurant import Restaurant
restaurant = Restaurant('KFC','fast food')
print(restaurant.restaurant_name)
运行结果:
KFC
9-11 导入 Admin 类:以为完成练习 9-8 而做的工作为基础,将 User、 Privileges 和Admin 类存储在一个模块中,再创建一个文件,在其中创建一个 Admin 实例并对其调用方法 show_privileges(),以确认一切都能正确地运行。
from admin import Admin
admin = Admin('Michael','Jordan')
admin.privilege.show_privileges()
运行结果:
Admin can add post
Admin can delete post
Admin can ban user
9-12 多个模块:将 User 类存储在一个模块中,并将 Privileges 和 Admin 类存储在另一个模块中。再创建一个文件,在其中创建一个 Admin 实例,并对其调用方法show_privileges(),以确认一切都依然能够正确地运行。
from AdminAndPrivilege import Admin
admin = Admin('Michael','Jordan')
admin.privilege.show_privileges()
运行结果:
Admin can add post
Admin can delete post
Admin can ban user
9-13 使用 OrderedDict: 在练习 6-4 中,你使用了一个标准字典来表示词汇表。请使用 OrderedDict 类来重写这个程序,并确认输出的顺序与你在字典中添加键—值对的顺序一致。
from collections import OrderedDict
glossary = OrderedDict()
glossary['string'] = 'A series of characters.'
glossary['comment'] = 'A note in a program that the Python interpreter ignores.'
glossary['list'] = 'A collection of items in a particular order.'
glossary['loop'] = 'Work through a collection of items, one at a time.'
glossary['dictionary'] = "A collection of key-value pairs."
glossary['key'] = 'The first item in a key-value pair in a dictionary.'
glossary['value'] = 'An item associated with a key in a dictionary.'
glossary['conditional test'] = 'A comparison between two values.'
glossary['float'] = 'A numerical value with a decimal component.'
glossary['boolean expression'] = 'An expression that evaluates to True or False.'
for word, definition in glossary.items():
print("\n" + word.title() + ": " + definition)
运行结果:
String: A series of characters.
Comment: A note in a program that the Python interpreter ignores.
List: A collection of items in a particular order.
Loop: Work through a collection of items, one at a time.
Dictionary: A collection of key-value pairs.
Key: The first item in a key-value pair in a dictionary.
Value: An item associated with a key in a dictionary.
Conditional Test: A comparison between two values.
Float: A numerical value with a decimal component.
Boolean Expression: An expression that evaluates to True or False.
9-14 骰子:模块 random 包含以各种方式生成随机数的函数,其中的 randint()返回一个位于指定范围内的整数,例如,下面的代码返回一个 1~6 内的整数:
from random import randint
x = randint(1, 6)
请创建一个 Die 类,它包含一个名为 sides 的属性,该属性的默认值为 6。编写一个名为 roll_die()的方法,它打印位于 1 和骰子面数之间的随机数。创建一个 6 面的骰子,再掷 10 次。
创建一个 10 面的骰子和一个 20 面的骰子,并将它们都掷 10 次。
from random import randint
class Die():
def __init__(self,sides=6):
self.sides = sides
def roll_die(self):
return randint(1,self.sides)
die6 = Die()
results = []
for i in range(10):
result = die6.roll_die()
results.append(result)
print(results)
die10 = Die(sides=10)
results = []
for i in range(10):
result = die10.roll_die()
results.append(result)
print(results)
die20 = Die(sides=20)
results = []
for i in range(10):
result = die20.roll_die()
results.append(result)
print(results)
运行结果:
[4, 3, 1, 1, 6, 5, 1, 6, 2, 3]
[4, 4, 6, 10, 3, 9, 2, 5, 1, 8]
[4, 13, 9, 14, 18, 4, 1, 18, 11, 5]