Python习题八---Python编程:从入门到实践9.1~9.14

餐馆

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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")
my_restaurant=Restaurant('Moon','aa')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
C:\python\python.exe D:/pythonProject1/demo1.py
The restaurant name is Moon
The cuisine type is aa
The restaurant is opening

Process finished with exit code 0

三家餐馆

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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")
my_restaurant=Restaurant('Moon','aa')
xiaoming_restaurant=Restaurant('Beep','bb')
xiaohong_restaurant=Restaurant('Lamb','cc')
my_restaurant.describe_restaurant()
print('\n')
xiaoming_restaurant.describe_restaurant()
print('\n')
xiaohong_restaurant.describe_restaurant()
C:\python\python.exe D:/pythonProject1/demo1.py
The restaurant name is Moon
The cuisine type is aa


The restaurant name is Beep
The cuisine type is bb


The restaurant name is Lamb
The cuisine type is cc

Process finished with exit code 0

用户

9-3 用户 :创建一个名为User 的类,其中包含属性first_name 和last_name ,还有用户简介通常会存储的其他几个属性。在类User 中定义一个名 为describe_user() 的方法,它打印用户信息摘要;再定义一个名为greet_user() 的方法,它向用户发出个性化的问候。 创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。

class User():
    def __init__(self,first_name,last_name,sex):
        self.first_name=first_name
        self.last_name=last_name
        self.sex=sex
    def describe_user(self):
        print("The first name is "+self.first_name.title())
        print("The last name is "+self.last_name.title())
        print("The sex is "+self.sex)
    def greet_user(self):
        print("Hello "+self.last_name.title())
lily_user=User('aa','lily','woman')
ross_user=User('zz','ross','woman')
david_uaer=User('vv','david','man')
lily_user.describe_user()
print('\n')
lily_user.greet_user()
print('\n')
ross_user.describe_user()
print('\n')
ross_user.greet_user()
print('\n')
david_uaer.describe_user()
print('\n')
david_uaer.greet_user()

C:\python\python.exe D:/pythonProject1/demo1.py
The first name is Aa
The last name is Lily
The sex is woman


Hello Lily


The first name is Zz
The last name is Ross
The sex is woman


Hello Ross


The first name is Vv
The last name is David
The sex is man


Hello David

Process finished with exit code 0

就餐人数

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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")
    def read_number_served(self):
        print("There are "+str(self.number_served)+"  people in the restaurant")
my_restaurant=Restaurant('Moon','aa')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
my_restaurant.read_number_served()
C:\python\python.exe D:/pythonProject1/demo1.py
The restaurant name is Moon
The cuisine type is aa
The restaurant is opening
There are 0  people in the restaurant

Process finished with exit code 0

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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")
    def set_number_served(self,n):
        self.number_served=n

    def increment_number_served(self, n):
        self.number_served += n
        return self.number_served

    def serve_number(self):
        print("This restaurant can serve " + str(self.number_served) + " people")

my_restaurant=Restaurant('Moon','aa')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
my_restaurant.set_number_served(50)
my_restaurant.serve_number()
my_restaurant.increment_number_served(30)
my_restaurant.serve_number()
C:\python\python.exe D:/pythonProject1/demo1.py
The restaurant name is Moon
The cuisine type is aa
The restaurant is opening
This restaurant can serve 50 people
This restaurant can serve 80 people

Process finished with exit code 0

尝试登录次数

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,sex):
        self.first_name=first_name
        self.last_name=last_name
        self.sex=sex
        self.login_attempts=0
    def describe_user(self):
        print("The first name is "+self.first_name.title())
        print("The last name is "+self.last_name.title())
        print("The sex is "+self.sex)
    def greet_user(self):
        print("\tHello "+self.last_name.title())
    def increment_login_attempts(self):
        self.login_attempts+=1
    def reset_login_attempts(self):
        self.login_attempts=0
        print("\tThe login attempt is reseted " + str(self.login_attempts))

lily_user=User('aa','lily','woman')
lily_user.describe_user()
lily_user.greet_user()
for n in range(5):
    lily_user.increment_login_attempts()
print(lily_user.login_attempts)
lily_user.reset_login_attempts()
print(lily_user.login_attempts)

冰淇淋小店

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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")

class IcecreanmStand(Restaurant):
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)
        self.flavour=['草莓','巧克力','蓝莓']
    def describe_flavour(self):
        print("有以下口味:")
        for i in self.flavour:
            print(i)

my_restaurant=IcecreanmStand('jj','aa')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
my_restaurant.describe_flavour()

C:\python\python.exe D:/pythonProject1/demo1.py
The restaurant name is Jj
The cuisine type is aa
The restaurant is opening
有以下口味:
草莓
巧克力
蓝莓

Process finished with exit code 0

管理员

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,sex):
        self.first_name=first_name
        self.last_name=last_name
        self.sex=sex
    def describe_user(self):
        print("The first name is "+self.first_name.title())
        print("The last name is "+self.last_name.title())
        print("The sex is "+self.sex)
    def greet_user(self):
        print("Hello "+self.last_name.title())
class Admin(User):
    def __init__(self,first_name,last_name,sex):
        super().__init__(first_name,last_name,sex)
        self.privileges=["can add post" ,"can delete post" ,"can ban user"]
    def show_privileges(self):
        print("The admin has the following permisssions:")
        for i in self.privileges:
            print(i)
ll_user=Admin('ll','lily','woman')
ll_user.describe_user()
ll_user.greet_user()
ll_user.show_privileges()
C:\python\python.exe D:/pythonProject1/demo1.py
The first name is Ll
The last name is Lily
The sex is woman
Hello Lily
The admin has the following permisssions:
can add post
can delete post
can ban user

Process finished with exit code 0

权限

9-8 权限:编写一个名为Privileges 的类,它只有一个属性——privileges ,其中存储了练习9-7 所说的字符串列表。将方法show_privileges() 移到这 个类中。在Admin 类中,将一个Privileges 实例用作其属性。创建一个Admin 实例,并使用方法show_privileges() 来显示其权限。

class User():
    def __init__(self,first_name,last_name,sex):
        self.first_name=first_name
        self.last_name=last_name
        self.sex=sex
    def describe_user(self):
        print("The first name is "+self.first_name.title())
        print("The last name is "+self.last_name.title())
        print("The sex is "+self.sex)
    def greet_user(self):
        print("Hello "+self.last_name.title())
        
class Admin(User):
    def __init__(self,first_name,last_name,sex):
        super().__init__(first_name,last_name,sex)
        self.privileges=Privileges()

class Privileges():
    def __init__(self):
        self.privileges=["can add post" ,"can delete post" ,"can ban user"]
    def show_privileges(self):
        print("The admin has the following permisssions:")
        for i in self.privileges:
            print(i)
ll_user=Admin('ll','lily','woman')
ll_user.describe_user()
ll_user.greet_user()

ll_user.privileges.show_privileges()
C:\python\python.exe D:/pythonProject1/demo1.py
The first name is Ll
The last name is Lily
The sex is woman
Hello Lily
The admin has the following permisssions:
can add post
can delete post
can ban user

Process finished with exit code 0

电瓶升级

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
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
	    self.odometer_reading += miles

class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()

class 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 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
my_tesla=ElectricCar('tesla','model s','2016')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()

C:\python\python.exe D:/pythonProject1/demo1.py
2016 Tesla Model S
This car has a 70-kWh battery.
This car can go approximately 240 miles on a full charge.
This car can go approximately 270 miles on a full charge.

Process finished with exit code 0

导入 Restaurant 类

9-10 导入 Restaurant 类 :将最新的Restaurant 类存储在一个模块中。在另一个文件中,导入Restaurant 类,创建一个Restaurant 实例,并调 用Restaurant 的一个方法,以确认import 语句正确无误

##main
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 name is "+self.restaurant_name.title())
        print("The cuisine type is "+self.cuisine_type)
    def open_restaurant(self):
        print("The restaurant is opening")


##demo
from main import Restaurant
my_new_car = Restaurant('aa', 'ss')
my_new_car.describe_restaurant()
my_new_car.open_restaurant()
D:\pythonprojects\venv\Scripts\python.exe D:/pythonprojects/demo1.py
The restaurant name is Aa
The cuisine type is ss
The restaurant is opening

Process finished with exit code 0

导入 Admin 类

9-11 导入 Admin 类 :以为完成练习9-8而做的工作为基础,将User 、Privileges 和Admin 类存储在一个模块中,再创建一个文件,在其中创建一个Admin 实例 并对其调用方法show_privileges() ,以确认一切都能正确地运行

##main
class User():
    def __init__(self, first_name, last_name, sex):
        self.first_name = first_name
        self.last_name = last_name
        self.sex = sex

    def describe_user(self):
        print("The first name is " + self.first_name.title())
        print("The last name is " + self.last_name.title())
        print("The sex is " + self.sex)

    def greet_user(self):
        print("Hello " + self.last_name.title())


class Admin(User):
    def __init__(self, first_name, last_name, sex):
        super().__init__(first_name, last_name, sex)
        self.privileges = Privileges()


class Privileges():
    def __init__(self):
        self.privileges = ["can add post", "can delete post", "can ban user"]

    def show_privileges(self):
        print("The admin has the following permisssions:")
        for i in self.privileges:
            print(i)


##demo  导入整个模块
import main
ll_user=main.Admin('ll','lily','woman')
ll_user.describe_user()
ll_user.greet_user()

ll_user.privileges.show_privileges()
D:\pythonprojects\venv\Scripts\python.exe D:/pythonprojects/demo1.py
The first name is Ll
The last name is Lily
The sex is woman
Hello Lily
The admin has the following permisssions:
can add post
can delete post
can ban user

Process finished with exit code 0

多个模块

9-12 多个模块 :将User 类存储在一个模块中,并将Privileges 和Admin 类存储在另一个模块中。再创建一个文件,在其中创建一个Admin 实例,并对其调用方 法show_privileges() ,以确认一切都依然能够正确地运行

##main
class User():
    def __init__(self, first_name, last_name, sex):
        self.first_name = first_name
        self.last_name = last_name
        self.sex = sex

    def describe_user(self):
        print("The first name is " + self.first_name.title())
        print("The last name is " + self.last_name.title())
        print("The sex is " + self.sex)

    def greet_user(self):
        print("Hello " + self.last_name.title())
        
##demo2
from main import User
class Admin(User):
    def __init__(self, first_name, last_name, sex):
        super().__init__(first_name, last_name, sex)
        self.privileges = Privileges()


class Privileges():
    def __init__(self):
        self.privileges = ["can add post", "can delete post", "can ban user"]

    def show_privileges(self):
        print("The admin has the following permisssions:")
        for i in self.privileges:
            print(i)

##demo1
from main import User
from demo2 import Admin, Privileges
ll_user=Admin('ll','lily','woman')
ll_user.describe_user()
ll_user.greet_user()

ll_user.privileges.show_privileges()

输出与之前一致

使用OrderedDict

9-13 使用OrderedDict :在练习6-4中,你使用了一个标准字典来表示词汇表。请使用OrderedDict 类来重写这个程序,并确认输出的顺序与你在字典中添加键 —值对的顺序一致。

from collections import OrderedDict
xx=OrderedDict()
xx['11']='aa'
xx['22']='bb'
for i,j in xx:
    print(i+"'s favourite food is "+j)
D:\pythonprojects\venv\Scripts\python.exe D:/pythonprojects/main.py
1's favourite food is 1
2's favourite food is 2

Process finished with exit code 0

骰子

9-14 骰子 :模块random 包含以各种方式生成随机数的函数,其中的randint() 返回一个位于指定范围内的整数,例如,下面的代码返回一个1~6内的整数:

from random import randint
class Die():
    def __init__(self,sides=6):
        self.sides=sides
    def roll_die(self):
        return randint(1,6)

die=Die()
for i in range(10):
    print(die.roll_die())

小结

在本章中,你学习了:如何编写类;如何使用属性在类中存储信息,以及如何编写方法,以让类具备所需的行为;如何编写方法__init__() ,以便根据类创建包含所需属性的实例。
你见识了如何修改实例的属性——包括直接修改以及通过方法进行修改。你还了解了:使用继承可简化相关类的创建工作;将一个类的实例用作另一个类的属性可让类更简洁。
你了解到,通过将类存储在模块中,并在需要使用这些类的文件中导入它们,可让项目组织有序。
你学习了Python标准库,并见识了一个使用模块collections 中的OrderedDict 类的示例。
最后,你学习了编写类时应遵循的Python约定。
在第10章中,你将学习如何使用文件,这让你能够保存你在程序中所做的工作,以及你让用户做的工作。你还将学习异常异 ,这是一种特殊的Python类,用于帮助你在发生错误时 采取相应的措施。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

看星河的兔子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值