赞
踩
本章介绍的内容是类,虽然书中篇幅不大,不过是重点章节之一。
创建一个名为
Restaurant
的类,其方法__init__()
设置两个属性:restaurant_name
和cuisine_type
。创建一个名为describe_restaurant()
的方法和一个名为open_restaurant()
的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。
根据这个类创建一个名为restaurant
的实例,分别打印其两个属性,再调用前述两个方法。
class Restaurant:
def __init__(self, n, t):
self.restaurant_name = n
self.cuisine_type = t
def describe_restaurant(self):
print("The restaurant is called " + self.restaurant_name + " and the cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print("We are ready for service!")
restaurant = Restaurant("JP", "Chinese")
restaurant.describe_restaurant()
restaurant.open_restaurant()
#输出
# The restaurant is called JP and the cuisine type is Chinese
# We are ready for service!
注意:类要紧跟
self
!
根据你为完成练习
9-1
而编写的类创建三个实例,并对每个实例调用方法describe_restaurant()
。
class Restaurant:
def __init__(self, n, t):
self.restaurant_name = n
self.cuisine_type = t
def describe_restaurant(self):
print("The restaurant is called " + self.restaurant_name + " and the cuisine type is " + self.cuisine_type)
def open_restaurant(self):
print("We are ready for service!")
restaurant1 = Restaurant("JP", "Chinese")
restaurant2 = Restaurant("JJ", "Guangdong")
restaurant3 = Restaurant("PP", "Chaoshan")
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
#输出
#The restaurant is called JP and the cuisine type is Chinese
#The restaurant is called JJ and the cuisine type is Guangdong
#The restaurant is called PP and the cuisine type is Chaoshan
创建一个名为
User
的类,其中包含属性first_name
和last_name
,还有用户简介通常会存储的其他几个属性。在类User
中定义一个名 为describe_user()
的方法,它打印用户信息摘要;再定义一个名为greet_user()
的方法,它向用户发出个性化的问候。
创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class User:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
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)
jp1 = User("JP", "Wang")
jp2 = User("JJ", "W")
jp3 = User("PP", 'w')
jp1.greet_user()
jp2.greet_user()
jp3.greet_user()
#输出
#Hello! JP Wang
#Hello! JJ W
#Hello! PP w
在为完成练习
9-1
而编写的程序中,添加一个名为number_served
的属性,并将其默认值设置为0
。根据这个类创建一个名为restaurant
的实例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。
添加一个名为set_number_served()
的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。 添加一个名为increment_number_served()
的方法,它让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就餐人数。
class Restaurant:
def __init__(self, n, t, ns):
self.restaurant_name = n
self.cuisine_type = t
self.number_served = ns
def describe_restaurant(self):
print("The restaurant is called " + self.restaurant_name + " and the cuisine type is " + self.cuisine_type + ", and there had been " + str(self.number_served) + " people been to here!")
def open_restaurant(self):
print("We are ready for service!")
restaurant = Restaurant("JP", "Chinese", 10)
restaurant.describe_restaurant()
restaurant.number_served = 5
restaurant.describe_restaurant()
#输出
#The restaurant is called JP and the cuisine type is Chinese, and there had been 10 people been to here!
#The restaurant is called JP and the cuisine type is Chinese, and there had been 5 people been to here!
在为完成练习
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, fn, ln):
self.first_name = fn
self.last_name = ln
self.login_attempts = 0
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)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
jp = User("JP", "Wang")
print(jp.login_attempts)
jp.increment_login_attempts()
print(jp.login_attempts)
jp.increment_login_attempts()
print(jp.login_attempts)
jp.reset_login_attempts()
print(jp.login_attempts)
#输出
#0
#1
#2
#0
冰淇淋小店是一种特殊的餐馆。编写一个名为
IceCreamStand
的类,让它继承你为完成练习9-1
或练习9-4
而编写的Restaurant
类。这两个版本的Restaurant
类都可以,挑选你更喜欢的那个即可。添加一个名为flavors
的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋的方法。创建一个IceCreamStand
实例,并调用这个方法。
class Restaurant:
def __init__(self, n, t, ns):
self.restaurant_name = n
self.cuisine_type = t
self.number_served = ns
def describe_restaurant(self):
print("The restaurant is called " + self.restaurant_name + " and the cuisine type is " + self.cuisine_type + ", and there had been " + str(self.number_served) + " people been to here!")
def open_restaurant(self):
print("We are ready for service!")
class IceCreamStand(Restaurant):
def __init__(self, n, t, ns):
super().__init__(n,t,ns)
self.flavors = ['Milk', 'Apple', 'Strawberry', 'Mango']
ics = IceCreamStand("JP", "Chinese", 10)
ics.describe_restaurant()
for flavor in ics.flavors:
print("The ice-cream stand has flavors like " + flavor)
#输出
#The restaurant is called JP and the cuisine type is Chinese, and there had been 10 #people been to here!
#The ice-cream stand has flavors like Milk
#The ice-cream stand has flavors like Apple
#The ice-cream stand has flavors like Strawberry
#The ice-cream stand has flavors like Mango
管理员是一种特殊的用户。编写一个名为
Admin
的类,让它继承你为完成练习9-3或练习9-5而编写的User 类。添加一个名为privileges 的属性,用于存储一个由字符串(如"can add post"
、"can delete post"
、"can ban user"
等)组成的列表。编写一个名为show_privileges()
的方法,它显示管理员的权限。创建一个Admin
实例,并调用这个方法。
class User:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
self.login_attempts = 0
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)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self, fn, ln, prv):
super().__init__(fn, ln)
self.privileges = prv
def show_privileges(self):
self.describe_user()
print("The admin has privileges that " + self.privileges)
jp = Admin("JP", "Wang", "Can ban user")
jp.show_privileges()
#输出
#The user's name is JP Wang
#The admin has privileges that Can ban user
注意!
super
要加括号(一开始没加括号把我坑惨了)
还是self
的问题
编写一个名为
Privileges
的类,它只有一个属性——privileges
,其中存储了练习9-7
所说的字符串列表。将方法show_privileges()
移到这个类中。在Admin
类中,将一个Privileges
实例用作其属性。创建一个Admin
实例,并使用方法show_privileges()
来显示其权限。
class User:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
self.login_attempts = 0
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)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self, fn, ln, prv):
super().__init__(fn, ln)
self.privileges = ['ban others', 'close the web', 'set someone free']
def show_privileges(self):
for privilege in self.privileges:
print("The admin has privileges that " + privilege)
jp = Admin("JP", "Wang")
jp.show_privileges()
#输出
#The admin has privileges that ban others
#The admin has privileges that close the web
#The admin has privileges that set someone free
在本节最后一个
electric_car.py
版本中,给Battery
类添加一个名为upgrade_battery()
的方法。这个方法检查电瓶容量,如果它不是85
,就将它设置为85
。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range()
,然后对电瓶进行升级,并再次调用get_range()
。你会看到这辆汽车的续航里程增加了。
class Battery:
def __init__(self, battery_size=60):
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
bat = Battery(70)
bat.get_range()
bat.upgrade_battery()
bat.get_range()
#输出
#This car can go approximately 240 miles on a full charge.
#This car can go approximately 270 miles on a full charge.
将最新的
Restaurant
类存储在一个模块中。在另一个文件中,导入Restaurant
类,创建一个Restaurant
实例,并调 用Restaurant
的一个方法,以确认import
语句正确无误。
#将Restaurant类放在mod1.py中,并且注意将mod1.py放在与主模块文件相同的目录下
#主模块如下:
from mod1 import Restaurant
restaurant = Restaurant("JP", "Chinese", 10)
restaurant.describe_restaurant()
#输出
#The restaurant is called JP and the cuisine type is Chinese, and there had been 10 people been to here!
以为完成练习
9-8
而做的工作为基础,将User
、Privileges
和Admin
类存储在一个模块中,再创建一个文件,在其中创建一个Admin
实例 并对其调用方法show_privileges()
,以确认一切都能正确地运行。
#将3个类都放在mod1.py中,并且注意将mod1.py放在与主模块文件相同的目录下,主模块代码如下:
jp = Admin("JP", "Wang")
jp.show_privileges()
#输出
#The admin has privileges that ban others
#The admin has privileges that close the web
#The admin has privileges that set someone free
将
User
类存储在一个模块中,并将Privileges 和Admin
类存储在另一个模块中。再创建一个文件,在其中创建一个Admin
实例,并对其调用方法show_privileges()
,以确认一切都依然能够正确地运行。
仍然可以正常运行,此处代码省略(作者巨无聊)
在练习
6-4
中,你使用了一个标准字典来表示词汇表。请使用OrderedDict
类来重写这个程序,并确认输出的顺序与你在字典中添加键—值对的顺序一致。
#原有程序
#language = {'str()':'Change other types into string', 'len()':'Get length of an array', 'del':'Delete a member in an union type', 'for':'Means loop', 'title()':'Print a string with an UPPER first char'}
#for key, value in language.items():
# print(key + ' : ' + value)
class OrderedDict:
def __init__(self, o, d):
self.order = o
self.definition = d
def printOrder(self):
print(self.order + ':' + self.definition)
languages = (OrderedDict('str()', 'Change other types into string'), OrderedDict('len()','Get length of an array'), OrderedDict('del','Delete a member in an union type'), OrderedDict('for','Means loop'), OrderedDict('title()','Print a string with an UPPER first char'))
for language in languages:
language.printOrder()
#输出
#str():Change other types into string
#len():Get length of an array
#del:Delete a member in an union type
#for:Means loop
#title():Print a string with an UPPER first char
模块
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, s = 6):
self.side = s
def roll_die(self):
print("The result of a " + str(self.side) + " die is " + str(randint(1, self.side)))
d1 = Die()
for i in range(1,11):
d1.roll_die()
print("----------")
d2 = Die(10)
for i in range(1,11):
d2.roll_die()
print("----------")
d3 = Die(20)
for i in range(1,11):
d3.roll_die()
#输出
#The result of a 6 die is 6
#The result of a 6 die is 1
#The result of a 6 die is 2
#The result of a 6 die is 6
#The result of a 6 die is 4
#The result of a 6 die is 4
#The result of a 6 die is 3
#The result of a 6 die is 4
#The result of a 6 die is 6
#The result of a 6 die is 3
#----------
#The result of a 10 die is 9
#The result of a 10 die is 1
#The result of a 10 die is 5
#The result of a 10 die is 9
#The result of a 10 die is 2
#The result of a 10 die is 2
#The result of a 10 die is 3
#The result of a 10 die is 1
#The result of a 10 die is 5
#The result of a 10 die is 6
#----------
#The result of a 20 die is 10
#The result of a 20 die is 16
#The result of a 20 die is 18
#The result of a 20 die is 17
#The result of a 20 die is 12
#The result of a 20 die is 14
#The result of a 20 die is 7
#The result of a 20 die is 6
#The result of a 20 die is 5
#The result of a 20 die is 16
要了解
Python
标准库,一个很不错的资源是网站Python Module of the Week
。请访问http://pymotw.com/
并查看其中的目录,在其中找一个你感兴趣的模块进行探索,或阅读模块collections
和random
的文档。
本题没有代码,上相关网站浏览文档即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。