《Python编程:从入门到实践》习题答案——第9章 类

Python编程 从入门到实践 动手试一试 第9章答案 9-1 餐馆 创建一个名为Restaurant的类。其方法__init__()设置两个属性: restaurant_name和cuisine_type 创建一个名为describe_restaurant()的方法和一个名为open_restaurant()的方法; 其中前者打印前述两项信息,而后者打印一条信息指出餐馆正在营业。 根据这个类创建一个名为restaurant的实例,分别打印其两个属性,... 阅读详情
AI摘要

本文介绍了Python中的类和对象实例,如Restaurant、User、Admin类的定义、方法和实例化,展示了如何创建餐厅对象、用户管理以及模块导入和使用,涉及数据结构(OrderedDict)和随机数生成(Dice)。

# 动手试一试
# 9-1 餐厅
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.title() + " is opening.")
        print(self.restaurant_name.title() + "'s food is " + self.cuisine_type)

    def open_restaurant(self):
        """餐厅营业时间"""
        print(self.restaurant_name + " is opening at 10:00~22:00.")

good = Restaurant('tilly', 'chinese')    
print(good.restaurant_name.title())
print(good.cuisine_type.title())        
good.describe_restaurant()
good.open_restaurant()                  

# 9-2 三家餐厅:重新创建三个实例
print("\n")
happy = Restaurant('hili', 'france')    
print(happy.restaurant_name.title())
print(happy.cuisine_type.title())       
happy.describe_restaurant()
happy.open_restaurant()               

print("\n")
nice = Restaurant('cidy', 'american')   
print(nice.restaurant_name.title())
print(nice.cuisine_type.title())     
nice.describe_restaurant()
nice.open_restaurant()                  

# 9-3 用户:有问题
class User():
    def __init__(self, first_name, last_name, tel, address):
        self.first_name = first_name
        self.last_name = last_name
        self.tel = tel
        self.address = address

    def describe_user(self):
        print(self.first_name + self.last_name + "的电话号码是:" + self.tel)
        print("他(她)的住址是:" + self.address)

    def greet_user(self):
        print(self.first_name + self.last_name + "您好,欢迎您来到安徽合肥!")

wang = User('王','三','124567899','上海')
wang.describe_user()
wang.greet_user()

print("\n")
zhang = User('张','五','4343555555','北京')
zhang.describe_user()
zhang.greet_user()

print("\n")
huang = User('黄','八','12308','香港')
huang.describe_user()
huang.greet_user()

# 9-4 就餐人数
class Restaurant():

    def __init__(self, restaurant_name, cuisine_type):  
        """初始化属性restaurant_name和cuisine_type"""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0                       

    def person(self):
        """定义这家餐厅有多少人吃饭"""
        print(self.restaurant_name.title() + "餐厅有" + str(self.number_served) + "人在吃饭。")

    def set_number_served(self,number1):
        self.number_served = number1                  
    def increment_number_served(self,number2):        
        self.number_served += number2

restaurant = Restaurant('tilly', 'chinese')
restaurant.person()                     

print("\n")
restaurant.number_served = 50
restaurant.person()                  

print("\n")
restaurant.set_number_served(20)         
restaurant.person()                     

print("\n")
restaurant.set_number_served(100)
restaurant.increment_number_served(80)
restaurant.person()

# 9-5 尝试登录次数:
class User():
    def __init__(self, first_name, last_name, tel, address):
        self.first_name = first_name
        self.last_name = last_name
        self.tel = tel
        self.address = address
        self.login_attempts = 0     

    def login_number(self):
        print(self.first_name + self.last_name + "总共注册了" + str(self.login_attempts) + "次。" )

    def increment_login_attempts(self,add_number):
        self.login_attempts += add_number                 

    def reset_login_attempts(self,reset_number):
        self.login_attempts = reset_number                    

zhang = User('张','三','23333333','香港')                      
zhang.increment_login_attempts(1)
zhang.increment_login_attempts(1)
zhang.increment_login_attempts(1)
zhang.increment_login_attempts(1)
zhang.increment_login_attempts(1)
zhang.increment_login_attempts(1)               
zhang.login_number()                            

print("\n")
zhang.reset_login_attempts(0)                   
zhang.login_number()                             

# 9-6 冰淇淋小店
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.title() + " is opening.")
        print(self.restaurant_name.title() + "'s food is " + self.cuisine_type)

    def open_restaurant(self):
        """餐厅营业时间"""
        print(self.restaurant_name + " is opening at 10:00~22:00.")


class IneCreamStand(Restaurant):    
    """继承9-4,冰淇淋特殊餐厅"""

    def __init__(self, restaruant_name, cuisine_type):
        super().__init__(restaruant_name, cuisine_type)
        self.flavors = ['vanilla', 'chocolate', 'durian']


    def print_flavors(self):        
        print("\n")
        for flavor in self.flavors:
            print(flavor)

restaurant_4 = IneCreamStand('麦当劳甜品站', '冰淇淋')
restaurant_4.print_flavors()




# 9-7 管理员:编写一个名为Admin的类,让他继承练习9-3的User类
class User():
    def __init__(self, first_name, last_name, tel, address):
        self.first_name = first_name
        self.last_name = last_name
        self.tel = tel
        self.address = address
        self.login_attempts = 0

    def login_number(self):
        print(self.first_name + self.last_name + "总共注册了" + str(self.login_attempts) + "次。" )
    def increment_login_attempts(self,add_number):
        self.login_attempts += add_number
    def reset_login_attempts(self,reset_number):
        self.login_attempts = reset_number

class Admin(User):
    """特殊的用户,管理员"""

    def __init__(self, privileges):
        self.privileges = privileges

    def show_privileges(self):
        for i in self.privileges:
            print(i)

my_Admin = Admin(["can add post", "can delete post", "cna ban user"])
my_Admin.show_privileges()

# 9-8 权限
class Privileges():
    def __init__(self, privileges):
        self.privileges = privileges

    def show_privileges(self):
        for i in self.privileges:
            print(i)

class Admin(Privileges):
    def __init__(self, privileges):
        super().__init__(privileges)

my_Admin = Admin(["can add post", "can delete post", "cna ban user"])
my_Admin.show_privileges()

# 9-9 电瓶升级
class Battery():
    def __init__(self, battery_size = 70):
        self.battery_size = battery_size

    def describe_battery(self):
        print(f"这辆车有{self.battery_size}千米的电池。")

    def upgrade_battery(self):
        if self.battery_size == 85:
            self.battery_size = 85
        else:
            self.battery_size = 85

    def get_range(self):
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270

        message = "这辆车可以跑" + str(range)
        message += "千米的路程"
        print(message)

my_tesla = Battery()
my_tesla.upgrade_battery()
my_tesla.get_range()

# 9-10 导入Restaurant类

# restaurant.py
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.title() + " is opening.")
        print(self.restaurant_name.title() + "'s food is " + self.cuisine_type)

    def open_restaurant(self):
        print(self.restaurant_name + " is opening at 10:00~22:00.")


class IneCreamStand(Restaurant):   

    def __init__(self, restaruant_name, cuisine_type):
        super().__init__(restaruant_name, cuisine_type)
        self.flavors = ['vanilla', 'chocolate', 'durian']


    def print_flavors(self):        
        print("\n")
        for flavor in self.flavors:
            print(flavor)


from restaurant import Restaurant,IneCreamStand

Restaurant = IneCreamStand('麦当劳甜品站', '冰淇淋')
Restaurant.print_flavors()

# 9-11 导入Admin类

# admin.py
class User():
    def __init__(self, first_name, last_name, tel, address):
        self.first_name = first_name
        self.last_name = last_name
        self.tel = tel
        self.address = address
        self.login_attempts = 0
    def login_number(self):
        print(self.first_name + self.last_name + "总共注册了" + str(self.login_attempts) + "次。" )
    def increment_login_attempts(self,add_number):
        self.login_attempts += add_number
    def reset_login_attempts(self,reset_number):
        self.login_attempts = reset_number

class Admin(User):
    def __init__(self, privileges):
        self.privileges = privileges
    def show_privileges(self):
        for i in self.privileges:
            print(i)

class Privileges():
    def __init__(self, privileges):
        self.privileges = privileges

    def show_privileges(self):
        for i in self.privileges:
            print(i)

class Admin(Privileges):
    def __init__(self, privileges):
        super().__init__(privileges)


from admin import User,Admin,Privileges

my_Admin = Admin(["can add post", "can delete post", "cna ban user"])
my_Admin.show_privileges()

# 9-12 多个模块

# user.py

class User():
    def __init__(self, first_name, last_name, tel, address):
        self.first_name = first_name
        self.last_name = last_name
        self.tel = tel
        self.address = address
        self.login_attempts = 0
    def login_number(self):
        print(self.first_name + self.last_name + "总共注册了" + str(self.login_attempts) + "次。" )
    def increment_login_attempts(self,add_number):
        self.login_attempts += add_number
    def reset_login_attempts(self,reset_number):
        self.login_attempts = reset_number


# privilegesadmin.py

from user import User

class Admin(User):
    def __init__(self, privileges):
        self.privileges = privileges
    def show_privileges(self):
        for i in self.privileges:
            print(i)
class Privileges():
    def __init__(self, privileges):
        self.privileges = privileges

    def show_privileges(self):
        for i in self.privileges:
            print(i)
class Admin(Privileges):
    def __init__(self, privileges):
        super().__init__(privileges)
from privilegesadmin import Privileges,Admin

my_Admin = Admin(["can add post", "can delete post", "cna ban user"])
my_Admin.show_privileges()

# 9-13 使用OrderedDict
from collections import OrderedDict

dics = OrderedDict()

dics['int'] = '整形'
dics['bool'] = '布尔类型'
dics['float'] = '浮点型'
dics['str'] = '字符串'
dics['list'] = '列表'

for k,v in dics.items():
    print(k + ':' + v)

# 9-14 骰子
from random import randint
x = randint(1, 6)
print(x)

from random import randint

class Die():
    def __init__(self):
        self.sides = 6

    def roll_die6(self):
        x = randint(1, 6)
        print(x)

    def roll_die10(self):
        x = randint(1, 10)
        print(x)

    def roll_die20(self):
        x = randint(1, 20)
        print(x)

my_die = Die()

print("------------6sides---------------")
for i in range(10):
	my_die.roll_die6()
print("------------10sides---------------")
for i in range(10):
	my_die.roll_die10()
print("------------20sides---------------")
for i in range(10):
	my_die.roll_die20()

# 9-15 Python Module of the Week



*Python编程:从入门到实践 第九章 类的练习题答案 前半部分 Python编程:从入门到实践 第九章 类的练习题答案 9-1 餐馆:创建一个名为Restaurant的类,其方法__init__()设置两个属性:restaurant_name和cuisine_type。创建一个名为describe_restaurant()的方法和一个名为open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200608 9-2 三家餐馆:根据你为 阅读详情

相关推荐

《Python编程从入门到实践》习题答案及重点

发现自己对于python的基础掌握的并不是很牢实,利用几天时间把重点写下来,并打算把(《Python编程从入门到实践》试一试)的代码全部敲一遍,如果有不对的地方,请不吝赐教。 目录 第1章 起步 第2章 变量和简单数据类型 第3章 列表简介 第4章 操作列表 第5章 if语句 第6章 字典 第7章 用户输入和while循环 第8章 函数 第9章 类 第10章 文件和...

qq_42364307的博客 3万+

Python编程:从入门到实践——练习题答案(第九章)

1.由类创建实例,实例的属性可以通过句点访问.2.修改类中属性的值:直接实例修改;定义方法进行设置;定义方法递增3.子类可以继承父类属性,定义新属性,方法冲突时在子类中编写同名方法函数即可重写父类方法。super()函数关联父类和子类。4.实例也可以作为属性赋给(见9.3.3例子)

huahuahuaaaa的博客 1633

《Python编程:从入门到实践》各章习题答案汇总

《Python编程:从入门到实践》各章习题答案汇总

jzhw_code的博客 1万+

《Python编程:从入门到实践》第 9 章 类

《Python编程:从入门到实践》第 9 章 类 主要内容及习题

weixin_63664072的博客 2352

Python编程从入门到实践第9章习题答案

#coding:gbk #9-1餐馆 class Restaurant(object): """一个典型的餐馆""" def __init__(self, name, cuisine_type): """初始化属性name和cuisine_type""" self.name = name self.cuisine_type = cuisine_type def

qq_42744540的博客 2127

Python编程:从入门到实践——练习题答案(第七章)

第7章 用户输入和while循环 7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息, 如“Let me see if I can find you a Subaru”。 car = input('What kind of car do you want to rent?') print('Let me see if I can find you a ' + car) 运...

森豪Steven的博客 7298

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):...

weixin_45508230的博客 940

Python编程从入门到实践第7章习题答案

#7-1汽车租赁 #coding:gbk #7-1汽车租赁 sorts = input("Please enter the kind of the car") print('Let me see if I can find you a ' + sorts) #7-2餐馆订位 number = input("Please enter the number of the catten") numbe...

qq_42744540的博客 794

Python编程:从入门到实践第9章习题答案

print('----9-1习题答案----')class Restaurant(): '''餐馆''' def __init__(self,restaurant_name,cuisine_type): """ 定义餐馆 """ self.restaurant_name=restaurant_name self.cuisine_type=cuisine_type def des...

laozi324的博客 2485

《Python编程:从入门到实践》第15章-15.9习题答案分享

python初学者,这里没找到答案,我写的答案和大家分享一下,有不对的地方希望大牛们指导 主程序 dice_visuel.py import pygal from die import Die die_1 = Die() die_2 = Die() result_x = [] for roll_number in range(1000): valuex = die_1.roll() * die_2.roll() result_x.append(valuex) result = set(re

m0_48922238的博客 898

Python编程从入门到实践第10章习题答案

#10-1Python学习笔记 file_path = 'E:\python_work\example\learing_python.txt' with open(file_path) as file_object: #print(file_object.read()) lines = file_object.readlines() # for line in lines: # pr...

qq_42744540的博客 1310

《python编程:从入门到实践》课后习题答案

https://www.xz577.com/j/129.html

miahhrgbfcyur的博客 7887

《Python程序设计入门与实践》219道课后习题答案

适用教材:Python程序设计入门与实践I S B N:978-7-5606-5960-2作 者:董付国页 数:319页例题数量:73个演示代码:200段(不含例题代码)习题数...

Python小屋 3546

Python编程从入门到实践 学习笔记+练习题答案导航

Python编程从入门到实践 练习题答案导航

Is_Superman的博客 990

Python编程从入门到实践第6章习题答案

#coding:gbk alien_0 = {'color':'green','point':5} get_point = alien_0['point'] print('You have get ' + str(get_point) + ' points') alien_0['x_position'] = 0 alien_0['y_position'] = 25 print('\n') pri...

qq_42744540的博客 785

python快速编程入门第二版课后编程题答案

1.对象2.可移植3.字节码4.UTF-8。

a17348的博客 2335

coursera Python交互编程入门 习题答案

以下代码是我的答案。仅供参考交流

King658的专栏 2540

python编程从入门到实践答案一

名言:找一句你钦佩的名人说的名言,将这个名人的姓名和他的名言打印出来。如果程序太简单,实在没有什么需要说明的,就在程序文件开头加上你的姓名和当前日期,再用一句话阐述程序的功能。名言2:重复练习2-5,但将名人的姓名存储在变量famous_person中,再创建要显示的消息,并将其存储在变量message中,然后打印这条消息。剔除人名中的空白:存储一个人名,并在其开头和末尾都包含一些空白字符。将你最喜欢的数字存储在一个变量中,再使用这个变量创建一条消息,指出你最喜欢的数字,然后将这条消息打印出来。

Jonathan的博客 1378
上一篇: 《Python编程:从入门到实践》习题答案——第8章 函数
下一篇: 《Python编程:从入门到实践》习题答案——第10章 文件和异常
广寒尔
博客等级 码龄3年 72粉丝 17原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值