Python编程:从入门到实践(课后习题:第9章 类)

coding=gbk

coding:utf-8!

chapter 9 practice

9-1餐馆

class Restaurant():
“”“简单创建一个名为restaurant的类”""
def init(self, name, type):
“”“设置name和type两个属性”""
self.name = name
self.type = type
def describe(self):
print(“The restaurant’s name is " + self.name.title()
+ " and it has " + self.type + " cuisine.”)
def open(self):
print(“The restaurant " + self.name.title()
+ " is now opening.”)
restaurant_1 = Restaurant(‘nayuki’, ‘western’) # 别忘了:实例=类()
restaurant_1.describe() # 注意这里实例与方法的位置:实例.方法
restaurant_1.open()

网上参考答案

print(“网上参考答案”)
class Restaurant():
def init(self,restaurant_name,cuisine_type):
“”“初始化属性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(‘Restaurant is open’)
restaurant = Restaurant(‘A’,‘B’)
print(restaurant.restaurant_name,’’,restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()

9-2三家餐馆

print("\n三家餐馆")
class Restaurant():
“”“简单创建一个名为restaurant的类”""
def init(self, name, type):
“”“设置name和type两个属性”""
self.name = name
self.type = type
def describe(self):
print(“The restaurant’s name is " + self.name.title()
+ " and it has " + self.type + " cuisine.”)
def open(self):
print(“The restaurant " + self.name.title()
+ " is now opening.”)
restaurant_1 = Restaurant(‘nayuki’, ‘Western’)
restaurant_2 = Restaurant(‘papa john’, ‘Italian’)
restaurant_3 = Restaurant(‘taco’, ‘Spanish’)
restaurant_1.describe()
restaurant_1.open()
restaurant_2.describe()
restaurant_2.open()
restaurant_3.describe()
restaurant_3.open()

9-3用户

print("\n用户")
class User():
def init(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def describe(self):
print("First name: " + self.first_name.title())
print("Last name: " + self.last_name.title())
def great_user(self):
print("Hello " + self.first_name.title() + " "
+ self.last_name.title() + “.”)
user_1 = User(‘tina’, ‘wang’)
user_2 = User(‘john’, ‘hu’)
user_3 = User(‘joseph’, ‘hu’)
user_1.describe()
user_1.great_user()
user_2.describe()
user_2.great_user()
user_3.describe()
user_3.great_user()

9-4就餐人数

print("\n9-4就餐人数")
class Restaurant():
“”“简单创建一个名为restaurant的类”""
def init(self, name, type):
“”“设置name和type两个属性”""
self.name = name
self.type = type
self.number_served = 0
def describe_restaurant(self):
print(“The restaurant’s name is " + self.name.title()
+ " and it has " + self.type + " cuisine.”)
def open_restaurant(self):
print(“The restaurant " + self.name.title()
+ " is now opening.”)
def read_number_served(self):
print(“The restaurant has served " + str(self.number_served)
+ " customers.”)
def set_number_served(self, number_info):
self.number_served = number_info
def add_number_served(self, add):
self.number_served += add

restaurant_1 = Restaurant(‘nayuki’, ‘western’)
restaurant_1.describe_restaurant()
restaurant_1.open_restaurant()

restaurant_1.read_number_served()

restaurant_1.number_served = 20
restaurant_1.read_number_served()

restaurant_1.set_number_served(30)
restaurant_1.read_number_served()

restaurant_1.add_number_served(100)
restaurant_1.read_number_served()

网上参考答案

print("\n网上参考答案")
class Restaurant(object):
“”“一个典型的餐馆”""
def init(self, name, cuisine_type):
“”“初始化属性name和cuisine_type”""
self.name = name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
“”“描述饭店的名字的种类”""
print("\nThe restaurant name is: " + self.name.title())
print(“The restaurant type is: " + self.cuisine_type)
def open_restaurant(self):
“”“描述正在营业””"
print(self.name.title() + " is oppening, welcome!")
def set_sever_number(self):
“”“正在吃饭人的数量”""
print("\nThe number of person have meat are: " + str(self.number_served))
def update_number(self, number):
if number >= self.number_served:
self.number_served = number
else:
print("\nYou can’t roll back any number!")
def increment_number_served(self, number):
“”“将服务过的人数已制定形式增加”""
self.number_served += number

restaurant = Restaurant(‘queen’, ‘chinese food’)
restaurant.number_served = 1500
restaurant.set_sever_number()

restaurant.update_number(200)
restaurant.set_sever_number()

restaurant.increment_number_served(300)
restaurant.set_sever_number()

9-5尝试登陆次数

print("\n9-5尝试登陆次数")
class User():
def init(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 1
def describe(self):
print("First name: " + self.first_name.title())
print("Last name: " + self.last_name.title())
def great_user(self):
print("Hello " + self.first_name.title() + " "
+ self.last_name.title() + “.”)
def read_login_attempts(self):
print(“The login attempts are:” + str(self.login_attempts)
+ “.”)
def increment_login_attempts(self, number):
self.login_attempts += number
def reset_login_attempts(self):
self.login_attempts = 0

user_1 = User(‘tina’, ‘wang’)
user_1.describe()
user_1.great_user()

user_1.read_login_attempts()

user_1.increment_login_attempts(5)
user_1.read_login_attempts()

user_1.reset_login_attempts()
user_1.read_login_attempts()

网上参考答案

print("\n网上参考答案9-5")
class User():
def init(self, first_name, last_name):
‘’‘主方法,内涵first_name,last_name两个形参’’’
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 0

def describe_user(self):
	'''打印用户名称方法'''
	print('用户名称为:' + self.first_name + self.last_name)
	# print('共登录用户量:' + str(self.login_attempts))
	print('共登录用户量:(重置中……)'+str(self.login_attempts))

def greet_user(self):
	'''打印问候'''
	print('你好! ' + self.first_name + self.last_name)

def increment_login_attempts(self,number):
	self.login_attempts += number
	print('共登录用户量:' + str(self.login_attempts))

def reset_login_attempts(self):
	self.login_attempts = 0

user_a = User(‘Ma’,‘Yun’)
user_a.describe_user()
user_a.increment_login_attempts(1)
user_a.increment_login_attempts(1)
user_a.increment_login_attempts(1)
user_a.reset_login_attempts()
user_a.describe_user()

9-6冰淇淋小店

print("\n9-6冰淇淋小店参考答案")
class Restaurant():
def init(self, restaurant_name, cuisine_type):
“”“初始化父类Restaurant属性”""
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(“Restaurant is open”)

class IceCreamStand(Restaurant):
def init(self, restaurant_name, cuisine_type):
# 子类中第一次__init__里面的self不要漏了!
super().init(restaurant_name, cuisine_type)
# 使用super()函数时,里面不需要self
self.flavors = [‘orange’, ‘apple’,]
def show_ice(self):
for i in self.flavors:
print(i)

IceCreamStand1 = IceCreamStand(‘beijingfandian’, ‘beijingcai’)
IceCreamStand1.describe_restaurant()
IceCreamStand1.show_ice()

9-7管理员

print("\n9-7管理员")
class User():
def init(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.login_attempts = 1
def describe(self):
print("First name: " + self.first_name.title())
print("Last name: " + self.last_name.title())
def great_user(self):
print("Hello " + self.first_name.title() + " "
+ self.last_name.title() + “.”)
def read_login_attempts(self):
print(“The login attempts are:” + str(self.login_attempts)
+ “.”)
def increment_login_attempts(self, number):
self.login_attempts += number
def reset_login_attempts(self):
self.login_attempts = 0

class Admin(User):
def init(self, first_name, last_name):
super().init(first_name, last_name)
self.privileges = [‘can add post’, ‘can delete post’,
‘can ban user’,]
def show_privileges(self):
for i in self.privileges:
print(i)

Admin1 = Admin(‘papa’, ‘john’)
Admin1.describe()
Admin1.show_privileges()

9-8权限

print("\n9-8权限网上参考答案")
class User():
def init(self, first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(‘用户名称为:’ + self.first_name + self.last_name)
def greet_user(self):
print('你好! ’ + self.first_name + self.last_name)

class Admin(User):
def init(self,first_name,last_name):
super().init(first_name,last_name)
self.b = Privileges()
# self.privileges = [‘can add post’,‘can del post’,‘can ban user’]
def show_privileges(self):
# print(self.privileges)
for i in self.privileges:
print(“管理员权限有:” + i)

class Privileges():
def init(self):
self.privileges = [‘can add post’,‘can del post’,‘can ban user’]
def show_privileges(self):
for i in self.privileges:
print(“管理员权限有:” + i)

Admin1 = Admin(‘Ma’,‘Yun’)
Admin1.b.show_privileges()

9-9电瓶升级

print("\n9-9电瓶升级网上参考答案")
class Car():
“”“docstring for 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
# 打印里程消息
def read_odometer(self):
print(“This car has " + str(self.odometer_reading) + " miles on it.”)
# 更新里程数
def update_odometer(self, milegeage):
if milegeage >= self.odometer_reading:
self.odometer_reading = milegeage
else:
print(“You can’t roll back an odometer!”)
def increment_odometer(self, miles):
self.odometer_reading += miles

class Battery():
“”“docstring for 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 upgrade_battery(self):
if self.battery_size != 85:
self.battery_size = 85
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)
self.upgrade_battery() # 注意这里!更新为85

class ElectricCar(Car):
“”“docstring for ElectricCar”""
def init(self, make, model, year):
super().init(make, model, year)
self.battery_size = Battery()
def describe_battery(self):
self.battery_size.describe_battery() # 这里注意!调用
def get_range(self):
self.battery_size.get_range() # 这里注意!调用

my_tesla = ElectricCar(‘tesla’, ‘model s’, 2016)
my_tesla.get_range() # 第一次
my_tesla.get_range() # 更新为85后再次

9-10导入Restaurant类

建立restaurant.py文件存储Restaurant类

print("\n导入Restaurant类-网上参考答案")
from restaurant import Restaurant

restaurant1 = Restaurant(‘A’, ‘B’)
print(restaurant1.restaurant_name, " ", restaurant1.cuisine_type)
restaurant1.describe_restaurant()
restaurant1.open_restaurant()
print(restaurant1.get_number_served())
restaurant1.set_number_served(2)
print(restaurant1.get_number_served())
restaurant1.increment_number_served(10)

9-11导入Admin类

print("\n导入Admin类")
from restaurant import Admin
admin = Admin(‘Alice’, ‘Bob’)
admin.show_privileges()

9-13使用OrderedDict

从模块collections中使用OrderedDict()函数

print("\n9-13使用OrderedDict")
from collections import OrderedDict
dics = OrderedDict()
dics[‘a’] = ‘apple’
dics[‘b’] = ‘boy’
dics[‘c’] = ‘cat’
dics[‘d’] = ‘dog’
for key, value in dics.items():
print(key.title() + " is for " + value.title())

9-14骰子

模块random包含以各种方式生成随机数的函数

其中randint()返回位于指定范围内的整数

print("\n9-14骰子网上参考答案")
from random import randint
class Die():
def init(self, sides=6):
self.sides = sides
def roll_die(self):
return randint(1, self.sides)
def roll_10(self):
for i in range(10):
print(self.roll_die())
print(“6面的骰子,投10次”)
touzi1 = Die()
touzi1.roll_10()
print("\n10面的骰子,投10次")
touzi2 = Die(10)
touzi2.roll_10()
print("\n20面的骰子,投10次")
touzi3 = Die(20)
touzi3.roll_10()

9-15Python Module of the Week

访问http://pymotw.com查看目录,查找感兴趣模块探索

或阅读模块collections和random文档

你可能感兴趣的:(Python)