创建一个名为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(f"The restaurant_name is {self.restaurant_name}.")
print(f"The cuisine_type is {self.cuisine_type}.")
def open_restaurant(self):
print("The restaurant is open")
restaurant = Restaurant("Shaxian snacks","Chinese restaurant")
restaurant.describe_restaurant()
restaurant.open_restaurant()
根据你为完成练习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(f"The restaurant_name is {self.restaurant_name}.")
print(f"The cuisine_type is {self.cuisine_type}.
")
def open_restaurant(self):
print("The restaurant is open")
restaurant_chinese = Restaurant("Shaxian snacks","Chinese restaurant")
restaurant_chinese.describe_restaurant()
restaurant_USA = Restaurant("Quiznos","American style")
restaurant_USA.describe_restaurant()
restaurant_Italian = Restaurant("benee italian restaurant","Italian")
restaurant_USA.describe_restaurant()
创建一个名为User 的类,其中包含属性first_name 和last_name ,还有用户简介通常会存储的其他几个属性。在类User 中定义一个名 为describe_user() 的方法,它打印用户信息摘要;再定义一个名为greet_user() 的方法,它向用户发出个性化的问候 创建多个表示不同用户的实例,并对每个实例都调用上述两个方法
-
添加一个名为set_number_served() 的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。
-
添加一个名为increment_number_served() 的方法,它让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就
餐人数。
class Users:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def describe_user(self):
print(f"Your named {self.first_name} {self.last_name}.")
def greet_user(self):
print(f"Welcome you,{self.first_name} {self.last_name}.")
user_1 = Users("Chandler","Bing")
user_1.describe_user()
user_1.greet_user()
在为完成练习9-1而编写的程序中,添加一个名为number_served 的属性,并将其默认值设置为0。根据这个类创建一个名为restaurant 的实 例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它
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(f"The restaurant_name is {self.restaurant_name}.")
print(f"The cuisine_type is {self.cuisine_type}.")
print(f"The number_served is {self.number_served}.
")
def open_restaurant(self):
print("The restaurant is open")
def set_number_served(self,number_served):
self.number_served = number_served
def increment_number_served(self,number_served):
self.number_served += number_served
restaurant = Restaurant("Shaxian snacks","Chinese restaurant")
restaurant.open_restaurant()
restaurant.describe_restaurant()
restaurant.number_served = 14
restaurant.open_restaurant()
restaurant.describe_restaurant()
restaurant.set_number_served(26)
restaurant.open_restaurant()
restaurant.describe_restaurant()
restaurant.increment_number_served(4)
restaurant.open_restaurant()
restaurant.describe_restaurant()
在为完成练习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 Users:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
self.logic_attempts = 0
def describe_user(self):
print(f"Your named {self.first_name} {self.last_name}.")
print(f"the logic_attempts is {self.logic_attempts}.")
def greet_user(self):
print(f"Welcome you,{self.first_name} {self.last_name}.")
def increment_log_attempts(self):
self.logic_attempts = 1
def reset_log_attempts(self):
self.logic_attempts = 0
User =Users("chandler","bing")
User.describe_user()
User.increment_log_attempts()
User.describe_user()
User.reset_log_attempts()
User.describe_user()
冰淇淋小店是一种特殊的餐馆。编写一个名为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(f"The restaurant_name is {self.restaurant_name}.")
print(f"The 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 displayFlavors(self):
print(f"the {self.restaurant_name} have following available:" )
for flavor in flavors:
print(' '+flavor)
flavors = ['strawberry','chocolate','blue cheery']
iceCreamStand = IceCreamStand("Haagen-Dazs","ice_cream_stand",flavors)
iceCreamStand.describe_restaurant()
iceCreamStand.displayFlavors()
管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承你为完成练习9-3或练习9-5而编写的User 类。添加一个名为privileges 的属性,用 于存储一个由字符串(如"can add post"、"can delete post"、"can ban user"等)组成的列表。编写一个名为show_privileges()的方法,它 显示管理员的权限。创建一个Admin 实例,并调用这个方法
class Users:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
self.logic_attempts = 0
def describe_user(self):
print(f"Your named {self.first_name} {self.last_name}.")
print(f"the logic_attempts is {self.logic_attempts}.")
def greet_user(self):
print(f"Welcome you,{self.first_name} {self.last_name}.")
def increment_log_attempts(self):
self.logic_attempts = 1
def reset_log_attempts(self):
self.logic_attempts = 0
class Admin(Users):
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):
print('the privileges have following available:')
for privilege in self.privileges:
print(' '+privilege)
admin = Admin('0X','Higos')
admin.show_privileges()
编写一个名为Privileges 的类,它只有一个属性——privileges ,其中存储了练习9-7 所说的字符串列表。将方法show_privileges() 移到这 个类中。在Admin 类中,将一个Privileges 实例用作其属性。创建一个Admin 实例,并使用方法show_privileges() 来显示其权限
class Privileges:
def __init__(self):
self.privileges = ['can add post','can delete post','can ban user']
def show_privileges(self):
print('the privileges have following available:')
for privilege in self.privileges:
print(' '+privilege)
class Users:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
self.logic_attempts = 0
def describe_user(self):
print(f"Your named {self.first_name} {self.last_name}.")
print(f"the logic_attempts is {self.logic_attempts}.")
def greet_user(self):
print(f"Welcome you,{self.first_name} {self.last_name}.")
def increment_log_attempts(self):
self.logic_attempts = 1
def reset_log_attempts(self):
self.logic_attempts = 0
class Admin(Users):
def __init__(self,first_name,last_name):
super().__init__(first_name,last_name)
self.privileges =Privileges()
admin = Admin('0X','Higos')
admin.privileges.show_privileges()
在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery()的方法。这个方法检查电瓶容量,如果它不是85,就将它设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_r ange() ,然后对电瓶进行升级,并再次调用get_range() 。你会看到这辆汽车的续航里程增加了
class Car:
"""A simple attempt to represent a car."""
def __init__(self,manufacturer,model,year):
"""Initialize attributes to describe a car."""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.manufacturer} {self.model}."
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self,mileage):
"""Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self,miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self,battery_size=85):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 85:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge.")
def upgrade_battery(self):
if self.battery_size != 100:
self.battery_size = 100
print("Upgraded the battery to 100 kWh.")
else:
print("The battery is already Upgraded.")
class ElectricCar(Car):
"""Represent aspects of a car,specific to electric vehicles."""
def __init__(self,manufacturer,model,year):
"""Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(manufacturer,model,year)
self.battery = Battery()
my_tesla_car = ElectricCar('tesla','model s',2019)
print(my_tesla_car.get_descriptive_name())
my_tesla_car.battery.describe_battery()
my_tesla_car.battery.get_range()
my_tesla_car.battery.upgrade_battery()
my_tesla_car.battery.get_range()
将最新的Restaurant 类存储在一个模块中。在另一个文件中,导入Restaurant 类,创建一个Restaurant 实例,并调用Restaurant 的一个方法,以确认import 语句正确无误
from restaurant import Restaurant
restaurant = Restaurant("Shaxian snacks","Chinese restaurant")
restaurant.open_restaurant()
restaurant.describe_restaurant()
以为完成练习9-8而做的工作为基础,将User 、Privileges 和Admin 类存储在一个模块中,再创建一个文件,在其中创建一个Admin 实例并对其调用方法show_privileges() ,以确认一切都能正确地运行
from Admin import Admin
admin = Admin('0X','Higos')
admin.privileges.show_privileges()
将User 类存储在一个模块中,并将Privileges 和Admin 类存储在另一个模块中。再创建一个文件,在其中创建一个Admin 实例,并对其调用方法show_privileges() ,以确认一切都依然能够正确地运行
#https://github.com/programming-book-practice/Python-Crash-Course-Homework/blob/master/chapter09/9-12.py
from admin import Admin
eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
eric.describe_user()
eric_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
eric.privileges.privileges = eric_privileges
print("
The admin " + eric.username + " has these privileges: ")
eric.privileges.show_privileges()
请创建一个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):
results = []
for roll_die in range(10):
result =randint(1,self.sides)
results.append(result)
print(f"10 rolles of a {self.sides}-sided die:", results)
die = Die()
die.roll_die()
die = Die(10)
die.roll_die()
die = Die(20)
die.roll_die()
“Make a list or tuple containing a series of 10 numbers and five letters. Randomly select four numbers or letters from the list and print a message saying that any ticket matching these four numbers or letters wins a prize.”
from random import randint
characters = [123,2534,35,45,53,16,7,28,9,0,'a','b','c','d','e']
results = []
while len(results) <4:
result = characters[randint(0,len(characters)-1)]
if result in results:
continue
results.append(result)
print("Any ticket matching these four numbers
or letters wins a prize",results)