面向青少年的 Python 教程(三)

原文:Python for teenagers

协议:CC BY-NC-SA 4.0

八、使用类和对象

到目前为止,我们已经介绍了一些非常标准的编程语言特性和实践。本章将延续这一传统;然而,这个主题乍一看可能有点难以把握。不过不要担心——你已经走到了这一步,我们已经看到你从一个磕磕绊绊的跟班变成了一个十足的野兽英雄。

如果你的父母在来自蛇发女怪星球的软泥人的攻击中幸存下来,他们会感到骄傲的,或者他们会的。继续前进…

本章将重点介绍一个被称为OOP面向对象编程的概念。你将会学到被称为classesobjectsconstructorssuperclassessubclasses的东西,以及一个被称为inheritance的强大工具。然后,我们将使用这些新的、强大的概念和方法来制作我们在第六章中创建的程序版本。

没错——就在你认为我们无法改进老的超级英雄发电机 3000 时,你的发电机真的让你大吃一惊!我希望你戴着头盔,因为我不会清理那些大脑!

OOP 是什么?

说实话,Python 实际上是一种面向对象的编程语言。不是每个人都这样使用它,也不是每个人都是 OOP 的粉丝——或者真正理解它的真正力量。有些人会认为用面向对象的方式编写会让 Python 变得不那么 Python 化;也就是说,他们认为使用处于面向对象编程核心的方法、类和对象会降低 Python 的可读性和用户友好性。

这种说法可能有些道理,但总的来说,程序员在可读性方面损失的东西,可以在效率、减少错误和良好的编程习惯方面得到弥补。此外,如果你遵循良好的代码文档的实践(正如我们一再讨论的那样),你的代码将非常具有可读性,因为你将在程序的每一部分清楚地陈述你的意图。

面向对象编程(OOP)就是创建可重用的代码。还记得我们如何讨论函数和模块的好处吗?这些规则同样适用于使用 OOP 实践。它对于更复杂或更长的程序来说是完美的,因为它允许您重用代码片段,并将所有内容保存在一个漂亮、紧凑、易于访问的包中。

到目前为止,我们主要依赖于被称为过程化编程的东西。过程代码本质上是按顺序出现的代码行,也是最常用的代码行。在这一章中,我们将改变这一切!

OOP 编程的核心概念——顺便提一下,这个概念也存在于许多其他编程语言中——涉及到被称为对象的东西。

什么是班级(我会被评分吗?)

别担心——我知道“阶级”这个词让你害怕,让你想起关于数学乐趣的长篇大论,或者讲述早期伊特鲁里亚人经济体系的有趣故事。在 Python 中,类要有趣得多;然而,尽管如此,事实上,在一张好的圆周率图中可以找到很多快乐。

蟋蟀

但是我跑题了。

一个类最好被描述为一个对象的 DNA 更好的是,您可以将它视为一个对象的蓝图,甚至是一个模板。这样想一个类:如果你要制造一辆汽车,你不会只是随意地把一些金属和橡胶轮胎钉在一起,然后抱最好的希望。如果你这样做了,你的车就不会跑得太远,也不会看起来那么棒!

相反,你应该创建一个蓝图——或者一个类——包含你希望你的汽车拥有的某些细节或者特性。此外——因为我们英雄程序员都是关于效率的——我们想要创建一个蓝图(类),当我们建造任何汽车时都可以使用。这样,当我们去制造另一种型号的汽车时,我们就不必重新制定计划了。

例如,如果我们为一辆汽车创建一个类,我们可能想说每辆汽车都有四个轮胎、一个挡风玻璃、门、一个引擎等等。这些都是每辆车都会有的普通东西。颜色、油漆、车门数量、轮胎尺寸等等可能不同,但是这些基本特征在每辆车上都会存在。

总而言之,类基本上是一个蓝图,它让我们创建多个具有相同基本特征的对象。每次我们创建一个新对象时,不必编码或定义这些特性,我们只需调用我们的类和 blammo 的一个实例,所有的工作都已经完成了。

如果这个概念还没有完全进入你的大脑,不要担心——当我们开始在实际代码中使用它时,它会变得非常清晰。现在,只需了解基本概念:

班级。都是。蓝图。

什么是对象

如果类是蓝图,那么对象就是我们从它们中创建的对象!用编程术语来说,当我们创建一个对象时,我们正在创建该类的一个实例

对象可以用来表示程序中的一系列事物。如上所述,例如,您可以使用它们来创建车辆。或者他们可以代表一个狗品种或一种类型的雇员。

当然,这是一本超级英雄编程书籍,那么还有什么比创建我们自己的超级英雄(对象)蓝图(类)更好的方式来介绍类和对象的概念——以及如何使用它们呢?

创建我们的第一个班级

创建一个类是一件相对简单的事情。事实上,这非常类似于创建一个函数。当我们创建一个类时——就像函数一样——它被称为定义一个类的*。我们使用关键字class来实现:*

*```py
class Superhero():

…(write some code)
…(more code here)


这个例子展示了如何创建一个名为超级英雄的类。注意类的命名约定是首字母大写。如果名字中有两个或更多的单词,你应该大写每个单词的第一个字母。例如,如果您想创建一个类来表示一个“美国超级英雄”,您可以使用:

```py
class AmericanSuperHero():
      ...(write some code)
      ...(write some more code)

当然,这些类在技术上不做任何事情。为了使它们有用并执行它们的功能,我们需要向它们添加代码,告诉它们做什么,或者帮助定义我们将从它们创建的对象。

当我们给一个类添加一个函数时,这个函数被称为method。方法必须缩进到它们所属的类之下。

class Superhero():
      def fly(self):
             print("Look at me, I'm so fly!")

这段代码用一个名为fly的方法创建了一个名为Superhero的类,它打印出文本“看看我,我飞得真快!”

当我们定义一个方法时,我们使用def,后跟方法名。方法包含封装在圆括号中的参数。类的每个方法必须至少包含self参数;它们也可以包含任意数量的其他参数(很快会有更多相关内容!).

self用来引用你创建的对象的实例。同样,这将更有意义,因为我们实际上创建了我们的类并让它们工作。

还要注意,方法定义下的代码也必须相对于它所属的方法缩进。

我们可以在一个类中放置任意数量的方法,也可以向它们添加各种代码,包括变量等等。

例如,如果我们想给我们的Superhero类添加两个方法——一个让他飞,另一个让他吃很多热狗——我们可以这样定义我们的类:

class Superhero():
      def fly(self):
             print("Look at me, I'm so fly!")

      def hotDog(self):
             print("I sure do like hot dogs!")

如果我们运行这段代码,什么也不会发生,因为我们所做的只是定义我们的Superhero类。为了实际使用这个类,我们必须创建这个类的一个实例或者一个对象。

创建我们的第一个对象

现在我们有了一个通过我们的Superhero类创建的超级英雄的基本蓝图,我们可以创建我们的第一个英雄,或者更恰当地说,我们的第一个英雄对象。

为了创建一个对象(或一个类的实例),我们必须初始化或创建一个类的副本,类似于创建一个变量并赋予它一个值:

HotDogMan = Superhero()

创建一个对象就是这么简单。现在,对象HotDogMan具有我们的Superhero类的所有特征。Superhero类的实例/对象存储在HotDogMan中,包括我们在创建该类时定义的所有属性和方法。

为了看到这一点,我们可以调用我们在超级英雄类中定义的两个方法,这两个方法现在是 HotDogMan 对象的一部分。调用意味着执行或运行部分代码:

HotDogMan.fly()
HotDogMan.hotDog()

这段代码的第一行告诉 Python 访问HotDogMan对象并寻找一个名为fly的方法,一旦找到,就执行它。第二行做同样的事情,只是它寻找方法hotDog并运行那部分代码。

为了更好地理解我们到目前为止所涉及的一切,让我们创建一个名为SampleClassandObject.py的新文件,并向其中添加以下代码(注意:该代码是我们到目前为止在本章中讨论过的代码,收集到一个文件中):

class Superhero():
      def fly(self):
             print("Look at me, I'm so fly!")

      def hotDog(self):
             print("I sure do like hot dogs!")

HotDogMan = Superhero()
HotDogMan.fly()
HotDogMan.hotDog()

当我们运行这段代码时,我们会得到以下结果:

Look at me, I'm so fly!
I sure do like hot dogs!

这一切都很好,但是,在现实中,这些例子并没有显示类和对象——以及面向对象的能力——所具有的真正能力。现在我们已经理解了类和对象的基本概念,让我们以一种更加实际和真实的方式来使用它们。

改进超级英雄生成器 3000!

如果你还记得第六章的话,我们创建了一个随机生成超级英雄的程序。具体来说,我们随机生成了一个超级英雄名,一个威能,和一些统计数据。为此,我们让用户运行程序,并在显示结果之前回答几个简单的问题。

我们按照非常连续的顺序创建了那个程序;也就是说,我们编写的代码被 Python 解释器——以及任何查看它的程序员——逐行读取。当程序运行时(我想补充的是,完美无缺!),如果我们要创造第二个,或者第一千个超级英雄,会发生什么?要做到这一点,在程序的当前状态下,用户必须一遍又一遍地运行程序。

效率不是很高。

如果用户请求多个英雄,我们可以一直创建一个循环来继续超级英雄的选择过程,或者我们可以继续添加更多的代码来允许更多的超级英雄,但是,我们希望创建尽可能少的代码行,以使我们的程序运行得更好,并减少出错的可能性。

请这样想:我们旧的超级英雄生成器 3000 程序是一个手工构建每个超级英雄的系统。如果我们使用类和对象,我们将拥有一个高科技工厂,可以打印出成千上万的超级英雄,而不必担心人为错误。此外,这将节省大量时间,因为我们不必写这么多代码。

记住所有这些,让我们尝试重新创建超级英雄生成器 3000,这一次利用类和对象。

如果你还记得的话,在我们最初版本的程序中,每个英雄都有一组定义他们身体和精神特征的统计数据。其中包括:

  • 大脑:主人公有多聪明

  • 布劳恩:英雄有多强

  • 耐力:英雄有多少能量

  • 智慧:他们有多聪明,有多少现实生活经验

  • 体质:他们的身体从伤害中恢复和抵抗疾病的能力

  • 灵巧:我们的英雄是多么的杂技和敏捷

  • 速度:英雄有多快

我们可以将这些属性分配给一个Superhero类,这样,当我们从该类创建一个对象时,我们创建的所有英雄都将拥有相同的统计数据。我们这样做是因为我们知道每个英雄都应该至少有一些头脑、头脑、敏捷等等——这些都是标准英雄的共同特征,因此,将成为我们英雄蓝图或模板的一部分。

让我们创建一个名为SuperHeroClass.py的新文件,并向其中添加以下代码:

# Import the random module so we can randomly generate numbers
import random

# Create a Superhero class

that will act as a template for any heroes we create
class Superhero():
    # Initializing our class and setting its attributes
    def __init__(self):
        self.superName = " "
        self.power = " "
        self.braun = braun
        self.brains = brains
        self.stamina = stamina
        self.wisdom = wisdom
        self.constitution = constitution
        self.dexterity = dexterity
        self.speed = speed

# Adding random values to each stat using the random() module
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)

在这段代码中,我们介绍了一种新方法,称为constructor方法。我们用它来初始化任何属于这个类的新数据。constructor方法也被称为__init__方法,当我们需要预先向任何变量添加数据时,它总是我们在类中创建的第一个方法。

我们将参数放在__init__方法的括号中,然后将每个self引用设置为等于每个参数。例如:

self.brains = brains

self.brains设置为等于brains。这样,以后在程序中创建我们的对象时,我们可以引用不同的参数——在本例中,这些参数代表我们的英雄统计数据——并在程序中使用它们。

接下来,在这种情况下,我们希望创建英雄模板,我们希望每个英雄统计数据是随机的,所以我们对每个代表英雄统计数据的参数使用 random()模块。例如:

braun = random.randint(1,20)

braun加一个随机值,范围从 1 到 20。

同样,对于初学者来说,类、对象和方法可能是一个很难掌握的主题,所以要有耐心,并确保遵循代码,即使事情没有马上 100%有意义;有时,您需要看到代码的运行,才能完全理解它的意图。

现在,我们已经建立了我们的初始超级英雄类,并决定了我们创建的任何超级英雄的模板将是什么样子,让我们继续尝试创建该类的一个实例(也称为创建一个对象)。然后,我们将打印出我们英雄的数据。将以下代码添加到 SuperheroClass.py 文件中:

# Import the random module so we can randomly generate numbers
import random
# Create a Superhero class that will act as a template for any heroes we create
class Superhero():
    # Initializing our class and setting its attributes
    def __init__(self):
        self.superName = superName
        self.power = power
        self.braun = braun
        self.brains = brains
        self.stamina = stamina
        self.wisdom = wisdom
        self.constitution = constitution
        self.dexterity = dexterity
        self.speed = speed

# Adding random values to each stat using the random() function
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)

print("Please enter your super hero name: ")

# Creating the Superhero object
hero = Superhero()

# Assigning a value to superName using the user's input

hero.superName = input('>')

# We print out the result of the created object, including its parameters
print("Your name is %s." % (hero.superName))
print("Your new stats are:")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed ", hero.speed)
print("")

在这个版本的程序中,我们要求用户为超级英雄输入他们自己的名字,而不是像我们在最初的超级英雄生成器 3000 程序中那样随机生成一个名字。不要担心——我们很快就会随机化这个值。现在,我们想保持事情简单,因为我们让用户输入他们自己的名字,使用input()函数。input()函数的值放在英雄对象的superName参数中。这一切都在生产线上实现:

hero.superName = input('>')

你可能已经注意到我们在这里使用的input()和以前有一点不同。括号中的'>'只是在用户的屏幕上放置一个>提示,这样他们就知道在哪里输入。

接下来,我们打印出了hero对象的每个参数的随机生成值,例如,如下所示:

print("Brains: ", hero.brains)

然后该行的, hero.brains部分告诉 Python 打印存储在hero对象brains参数中的值——类似于变量的工作方式。

如果您运行该程序,您将得到如下结果——请记住,您的值会有所不同,因为它们是随机生成的:

Please enter your super hero name:
>SuperPowerAwesomeManofAction
Your name is SuperPowerAwesomeManofAction.
Your new stats are:

Brains:  10
Braun:  10
Stamina:  5
Wisdom:  17
Constitution:  1
Dexterity:  19
Speed  15

完美到目前为止!现在,让我们添加代码来随机生成英雄的名字和超能力。对于这一部分,我们将添加以下行:

# Creating a list of possible super powers

superPowers = ['Flying', 'Super Strength', 'Telepathy', 'Super Speed', 'Can Eat a Lot of Hot Dogs', 'Good At Skipping Rope']

# Randomly choosing a super power from the superPowers list
# and assigning it to the variable power

power = random.choice(superPowers)

# Creating lists of possible first and last names

superFirstName = ['Wonder','Whatta','Rabid','Incredible', 'Astonishing', 'Decent', 'Stupendous', 'Above-average', 'That Guy', 'Improbably']

superLastName = ['Boy', 'Man', 'Dingo', 'Beefcake', 'Girl', 'Woman', 'Guy', 'Hero', 'Max', 'Dream', 'Macho Man','Stallion']

# Randomizing Super Hero Name
# We do this by choosing one name from each of our two name lists
# And adding it to the variable superName

superName = random.choice(superFirstName)+ " " +random.choice(superLastName)

就在我们定义超级英雄属性的地方。由于我们现在随机生成超级英雄的名字,我们不再需要用户输入,所以我们删除了这些行:

print("Please enter your super hero name: ")

# Assigning a value to superName using the user's input
hero.superName = input('>')

我们不再需要这些,因为我们现在从superFirstNamesuperLastName列表中随机生成superName,就像我们在程序的原始版本中所做的一样。

所以现在,所有这些加在一起,你的代码应该如下所示:如果没有,请再次查看这一部分,并更改您的代码以匹配我的代码:

# Import the random module so we can randomly generate numbers
import random

# Create a Superhero class that will act as a template for any heroes we create
class Superhero():
    # Initializing our class and setting its attributes
    def __init__(self):
        self.superName = superName
        self.power = power
        self.braun = braun
        self.brains = brains
        self.stamina = stamina
        self.wisdom = wisdom
        self.constitution = constitution
        self.dexterity = dexterity
        self.speed = speed

# Adding random values to each stat using the random() function
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)

# Creating a list of possible super powers

superPowers = ['Flying', 'Super Strength', 'Telepathy', 'Super Speed', 'Can Eat a Lot of Hot Dogs', 'Good At Skipping Rope']

# Randomly choosing a super power from the superPowers list
# and assigning it to the variable power

power = random.choice(superPowers)

# Creating lists of possible first and last names

superFirstName = ['Wonder','Whatta','Rabid','Incredible', 'Astonishing', 'Decent', 'Stupendous', 'Above-average', 'That Guy', 'Improbably']

superLastName = ['Boy', 'Man', 'Dingo', 'Beefcake', 'Girl', 'Woman', 'Guy', 'Hero', 'Max', 'Dream', 'Macho Man','Stallion']

# Randomizing Super Hero Name
# We do this by choosing one name from each of our two name lists
# And adding it to the variable superName

superName = random.choice(superFirstName)+ " " +random.choice(superLastName)

print("Please enter your super hero name: ")

# Creating the Superhero object
hero = Superhero()

# Assigning a value to superName using the user's input
# hero.superName = input('>')

# We print out the result of the created object, including its parameters
print("Your name is %s." % (hero.superName))
print("Your super power is: ", power)
print("Your new stats are:")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed ", hero.speed)
print("")

如果您现在运行这个程序,您将得到以下结果(同样,您的值将会不同,因为它们是随机生成的):

Please enter your super hero name:
Your name is Incredible Dream.
Your super power is:  Good At Skipping Rope
Your new stats are:

Brains:  1
Braun:  1
Stamina:  5
Wisdom:  11
Constitution:  6
Dexterity:  9
Speed  13

所以现在,在这一点上,我们的程序几乎与超级英雄生成器 3000 的原始版本一样,只是代码行更少,发生错误的机会更少。一些提示也是不同的——例如,我们还没有询问用户是否想要创建一个英雄,我们还没有在生成值时插入戏剧性的暂停效果。然而,基本框架已经到位,在下一节中,我们将添加一些旧的功能,以及一些新的、非常酷的功能,展示类和对象的真正威力!

继承,子类,等等!

类的一个伟大之处在于,你可以用它们来创建其他的类,并且通过一个叫做inheritance的东西,将它们的属性传递给新创建的类,而不必使用一堆冗长的代码。这类似于你的父母把他们的遗传密码传给你,只是在 Python 中,我们可以说一个类到底继承了什么。

当我们基于另一个类创建一个类时,我们称这个新创建的类为subclass。默认情况下,这些子类继承了创建它们的类的方法和参数——顺便说一下,这些方法和参数被称为父类或超类。

与所有代码一样,有时最好通过一个实际的程序来演示这个想法是如何工作的。

到目前为止,超级英雄生成器 3000 只让我们创建常规的旧超级英雄。然而,正如你所知,并不是所有的英雄都是平等的。例如,从技术上来说,超人只是一个来自另一个星球的外星人,他可以看穿衣服,吃阳光(像一棵黄色植物)来变得强壮。与此同时,蝙蝠侠完全没有超能力;或者更确切地说,他的超能力包括拥有一船的钱,一辆很棒的车,和一个拥有一些牵强的计算机编程技能的管家。我是说,真的吗?我的父母不会发短信,而阿尔弗雷德正在使用世界上最强大的超级电脑。

但是我跑题了。

为了让我们的程序更加真实,我们将为超级英雄引入一个新的属性:超级英雄类型。对于我们创造的每一种类型,我们将给予他们某种形式的奖金。现在,让我们专注于创建两个子类来表示我们新的英雄“类型”。一个是机器人超级英雄,另一个是变异的超级英雄。

下面是它在代码中的样子:

# Creating a subclass of Superhero named Mutate
# Mutate heroes will get a +10 bonus to their speed score.

class Mutate(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a Mutate!")
      self.speed = self.speed + 10

# Creating a subclass of Superhero named Robot
# Robot heroes will get a + 10 bonus to their braun score.

class Robot(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a robot!")
      self.braun = self.braun + 10

这里,我们创建了两个新类,它们实际上都是我们的Superhero类的子类。我们实现这一点的方法是将父类的名称放在新创建的类的括号中。例如:class Mutate(Superhero)告诉 Python 解释器创建一个类,这个类是 Superhero 的子类或子类,并继承它的方法和参数。

然后,我们使用def __init__(self)初始化我们的新子类,并使用Superhero.__init__(self)重新初始化我们的Superhero类,因为从技术上讲,我们将基于类和子类创建新对象。

最后,我们想给我们的英雄一个基于英雄类型的奖励。变异字符将获得速度加成,如这行代码所示:

self.speed = self.speed + 10

而机器人将通过这行代码获得对布劳恩的奖励:

self.braun = self.braun + 10

所有其他英雄属性将保持不变,因为它们最初是在超级英雄职业中产生的;如果我们想再次修改它们的值,我们必须在新创建的子类中显式地这样做。

现在我们已经创建了两个新类,我们需要实际创建一个基于它们的实例/对象来查看它们的运行情况。基于子类创建对象的代码与基于任何类创建对象的代码是一样的;如果我们想创建一个新的变异英雄和一个新的机器人英雄,我们可以使用以下代码行:

hero2 = Robot()

hero3 = Mutate()

让我们创建一些代码来打印普通超级英雄、机器人和变异人的统计数据:

# Creating the Superhero object
hero = Superhero()

# We print out the result of the created object, including its parameters
print("Your name is %s." % (hero.superName))
print("Your super power is: ", hero.power)
print("Your new stats are:")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed ", hero.speed)
print("")

# Creating a Mutate object

hero2 = Mutate()
print("Your name is %s." % (hero2.superName))
print("Your super power is: ", hero2.power)
print("Your new stats are:")
print("")
print("Brains: ", hero2.brains)
print("Braun: ", hero2.braun)
print("Stamina: ", hero2.stamina)
print("Wisdom: ", hero2.wisdom)
print("Constitution: ", hero2.constitution)
print("Dexterity: ", hero2.dexterity)
print("Speed ", hero2.speed)
print("")

# Create a Robot character

hero3 = Robot()
print("Your name is %s." % (hero3.superName))
print("Your super power is: ", hero3.power)
print("Your new stats are:")
print("")
print("Brains: ", hero3.brains)
print("Braun: ", hero3.braun)
print("Stamina: ", hero3.stamina)
print("Wisdom: ", hero3.wisdom)
print("Constitution: ", hero3.constitution)
print("Dexterity: ", hero3.dexterity)
print("Speed ", hero3.speed)
print("")

如果您将所有这些新代码添加到您的文件中(我们一会儿就会这样做)并运行它,您的结果将与此类似:

Your name is Above-average Boy.
Your super power is:  Flying
Your new stats are:

Brains:  16
Braun:  4
Stamina:  4
Wisdom:  18
Constitution:  16
Dexterity:  12
Speed  2

You created a Mutate!
Your name is Above-average Boy.
Your super power is:  Flying
Your new stats are:

Brains:  16
Braun:  4
Stamina:  4
Wisdom:  18
Constitution:  16
Dexterity:  12
Speed  12

You created a robot! 

Your name is Above-average Boy.
Your super power is:  Flying
Your new stats are:

Brains:  16
Braun:  14
Stamina:  4
Wisdom:  18
Constitution:  16
Dexterity:  12
Speed  2

注意普通超级英雄的速度是 2,机器人也是。然而变异的速度是 12。同样,我们的普通英雄和变异人的布劳恩为 4,而我们的机器人的布劳恩为 14——正如预期的那样。

此时,如果您添加新代码,您的SuperheroClass.py文件应该如下所示——如果不是,请花时间确保它是这样的:

# Import the random module so we can randomly generate numbers
import random

# Create a Superhero class

that will act as a template for any heroes we create
class Superhero():
    # Initializing our class and setting its attributes
    def __init__(self):
        self.superName = superName
        self.power = power
        self.braun = braun
        self.brains = brains
        self.stamina = stamina
        self.wisdom = wisdom
        self.constitution = constitution
        self.dexterity = dexterity
        self.speed = speed

# Adding random values to each stat using the random() function
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)

# Creating a list of possible super powers

superPowers = ['Flying', 'Super Strength', 'Telepathy', 'Super Speed', 'Can Eat a Lot of Hot Dogs', 'Good At Skipping Rope']

# Randomly choosing a super power from the superPowers list
# and assigning it to the variable power

power = random.choice(superPowers)

# Creating lists of possible first and last names

superFirstName = ['Wonder','Whatta','Rabid','Incredible', 'Astonishing', 'Decent', 'Stupendous', 'Above-average', 'That Guy', 'Improbably']

superLastName = ['Boy', 'Man', 'Dingo', 'Beefcake', 'Girl', 'Woman', 'Guy', 'Hero', 'Max', 'Dream', 'Macho Man','Stallion']

# Randomizing Super Hero Name
# We do this by choosing one name from each of our two name lists
# And adding it to the variable superName

superName = random.choice(superFirstName)+ " " +random.choice(superLastName)

# Creating a subclass of Superhero named Mutate

# Mutate heroes will get a +10 bonus to their speed score.

class Mutate(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a Mutate!")
      self.speed = self.speed + 10

# Creating a subclass of Superhero named Robot
# Robot heroes will get a + 10 bonus to their braun score.

class Robot(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a robot!")
      self.braun = self.braun + 10

# Creating the Superhero object

hero = Superhero()

# We print out the result of the created object, including its parameters
print("Your name is %s." % (hero.superName))
print("Your super power is: ", hero.power)
print("Your new stats are:")
print("")
print("Brains: ", hero.brains)
print("Braun: ", hero.braun)
print("Stamina: ", hero.stamina)
print("Wisdom: ", hero.wisdom)
print("Constitution: ", hero.constitution)
print("Dexterity: ", hero.dexterity)
print("Speed ", hero.speed)
print("")

# Creating a Mutate object

hero2 = Mutate()
print("Your name is %s." % (hero2.superName))
print("Your super power is: ", hero2.power)
print("Your new stats are:")
print("")
print("Brains: ", hero2.brains)
print("Braun: ", hero2.braun)
print("Stamina: ", hero2.stamina)
print("Wisdom: ", hero2.wisdom)
print("Constitution: ", hero2.constitution)
print("Dexterity: ", hero2.dexterity)
print("Speed ", hero2.speed)
print("")

# Create a Robot character

hero3 = Robot()
print("Your name is %s." % (hero3.superName))
print("Your super power is: ", hero3.power)
print("Your new stats are:")
print("")
print("Brains: ", hero3.brains)
print("Braun: ", hero3.braun)
print("Stamina: ", hero3.stamina)
print("Wisdom: ", hero3.wisdom)
print("Constitution: ", hero3.constitution)
print("Dexterity: ", hero3.dexterity)
print("Speed ", hero3.speed)
print("")

添加铃铛和哨子

我们现在需要做的最后一件事是给我们的程序添加一些附加功能。记住,这一章的目标是学习如何使用面向对象的编程来用那些原则重新制作我们的超级英雄生成器 3000 程序;我们的原始版本有一些戏剧性的停顿,并问了用户一些问题。在这里,我们将把所有这些特性添加回我们的程序中,并让他们选择英雄类型。

我们将使用到目前为止在本书中学到的原则,包括if-elif-else语句、random()input()time()模块,当然,还有这一章的 OOP 原则。

作为一个练习,我将重点介绍我们现在要添加的代码的一些主要特性,然后完整地输入程序,供您自己阅读和编码,而不是向您重复代码的每一步。

首先,我们希望为用户提供一个选择,就像我们在最初的程序中所做的那样——主要是,我们询问他们是否想使用超级英雄生成器 3000。如果他们选择“Y”,程序继续;如果没有,循环继续询问他们是否要继续:

# Introductory text

print("Are you ready to create a super hero with the Super Hero Generator 3000?")

# Ask the user a question and prompt them for an answer
# input() 'listens' to what they type on their keyboard
# We then use upper() to change the users answer to all uppercase letters

print("Enter Y/N:")

answer = input()
answer = answer.upper())

# While loop to check for the answer "Y"
# This loop will continue while the value of answer IS NOT "Y"
# Only when the user types "Y" will the loop exit and the program continue

while answer != "Y":
    print("I'm sorry, but you have to choose Y to continue!")
    print("Choose Y/N:")
    answer = input()
    answer = (answer.upper())

print("Great, let's get started!")

同样,这是我们程序的原始版本的代码,我们只是把它添加到了新版本中,所以你应该熟悉它的用法。

接下来,我们要添加一些品牌的新代码。这个新代码的目的是让用户选择他们想要创建的英雄的类型。我们给他们三个选择:常规,变异,或机器人。

# Letting the user choose which type of hero to create
print("Choose from the following hero options: ")
print("Press 1 for a Regular Superhero")
print("Press 2 for a Mutate Superhero")
print("Press 3 for a Robot Superhero")
answer2 = input()

接下来是一个if-elif-else块,它将检查用户答案的值——我们将其存储在变量answer2中——并做出相应的响应。例如,如果用户选择选项 1,将创建一个普通的超级英雄;选项 2,a 变异;等等。

下面是代码块:

if answer2=='1':

    # Creating the Superhero object
    hero = Superhero()

    # We print out the result of the created object, including its parameters
    print("You created a regular super hero!")
    print("Generating stats, name, and super powers.")

    # Creating dramatic effect

    for i in range(1):
        print("...........")
        time.sleep(3)

        print("(nah...you wouldn't like THAT one...)")

    for i in range(2):
        print("...........")
        time.sleep(3)

    print("(almost there....)")
    print(" ")
    print("Your name is %s." % (hero.superName))
    print("Your super power is: ", hero.power)
    print("Your new stats are:")
    print("")
    print("Brains: ", hero.brains)
    print("Braun: ", hero.braun)
    print("Stamina: ", hero.stamina)
    print("Wisdom: ", hero.wisdom)
    print("Constitution: ", hero.constitution)
    print("Dexterity: ", hero.dexterity)
    print("Speed ", hero.speed)
    print("")

elif answer2=='2':
        # Creating a Mutate object
        hero2 = Mutate()
        print("Generating stats, name, and super powers.")

    # Creating dramatic effect

        for i in range(1):
            print("...........")
            time.sleep(3)

            print("(nah...you wouldn't like THAT one...)")

        for i in range(2):
            print("...........")
            time.sleep(3)

        print("Your name is %s." % (hero2.superName))
        print("Your super power is: ", hero2.power)
        print("Your new stats are:")
        print("")
        print("Brains: ", hero2.brains)
        print("Braun: ", hero2.braun)
        print("Stamina: ", hero2.stamina)
        print("Wisdom: ", hero2.wisdom)
        print("Constitution: ", hero2.constitution)
        print("Dexterity: ", hero2.dexterity)
        print("Speed ", hero2.speed)
        print("")

elif answer2=='3':
        # Create a Robot character

        hero3 = Robot()

        print("Generating stats, name, and super powers.")

        # Creating dramatic effect

        for i in range(1):
            print("...........")
            time.sleep(3)

        print("(nah...you wouldn't like THAT one...)")

        for i in range(2):
            print("...........")
            time.sleep(3)

        print("Your name is %s." % (hero3.superName))
        print("Your super power is: ", hero3.power)
        print("Your new stats are:")
        print("")
        print("Brains: ", hero3.brains)
        print("Braun: ", hero3.braun)
        print("Stamina: ", hero3.stamina)
        print("Wisdom: ", hero3.wisdom)
        print("Constitution: ", hero3.constitution)
        print("Dexterity: ", hero3.dexterity)
        print("Speed ", hero3.speed)
        print("")
else:
        print("You did not choose the proper answer! Program will now self-destruct!")

最后,我们还需要import time否则我们的戏剧效果不会起作用!我们在代码的最顶端,在我们的import random语句下面这样做。

新的和改进的超级英雄生成器 3000 代码!

现在我们已经对所有的部分进行了编码,让我们确保它们都是有序的。将您的代码与下面的代码进行比较,确保一切都匹配。然后,运行程序几次,尝试所有选项,看看程序如何工作:

# Import the random module so we can randomly generate numbers
# Import time module for dramatic pausing effect
import random
import time

# Create a Superhero class

that will act as a template for any heroes we create
class Superhero():
    # Initializing our class and setting its attributes
    def __init__(self):
        self.superName = superName
        self.power = power
        self.braun = braun
        self.brains = brains
        self.stamina = stamina
        self.wisdom = wisdom
        self.constitution = constitution
        self.dexterity = dexterity
        self.speed = speed

# Adding random values to each stat using the random() function
braun = random.randint(1,20)
brains = random.randint(1,20)
stamina = random.randint(1,20)
wisdom = random.randint(1,20)
constitution = random.randint(1,20)
dexterity = random.randint(1,20)
speed = random.randint(1,20)

# Creating a list of possible super powers

superPowers = ['Flying', 'Super Strength', 'Telepathy', 'Super Speed', 'Can Eat a Lot of Hot Dogs', 'Good At Skipping Rope']

# Randomly choosing a super power from the superPowers list
# and assigning it to the variable power

power = random.choice(superPowers)

# Creating lists of possible first and last names

superFirstName = ['Wonder','Whatta','Rabid','Incredible', 'Astonishing', 'Decent', 'Stupendous', 'Above-average', 'That Guy', 'Improbably']

superLastName = ['Boy', 'Man', 'Dingo', 'Beefcake', 'Girl', 'Woman', 'Guy', 'Hero', 'Max', 'Dream', 'Macho Man','Stallion']

# Randomizing Super Hero Name

# We do this by choosing one name from each of our two name lists
# And adding it to the variable superName

superName = random.choice(superFirstName)+ " " +random.choice(superLastName)

# Creating a subclass of Superhero named Mutate
# Mutate heroes will get a +10 bonus to their speed score.

class Mutate(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a Mutate!")
      self.speed = self.speed + 10

# Creating a subclass of Superhero named Robot

# Robot heroes will get a + 10 bonus to their braun score.

class Robot(Superhero):
    def __init__(self):
      Superhero.__init__(self)
      print("You created a robot!")
      self.braun = self.braun + 10

# Introductory text

print("Are you ready to create a super hero with the Super Hero Generator 3000?")

# Ask the user a question and prompt them for an answer
# input() 'listens' to what they type on their keyboard
# We then use upper() to change the users answer to all uppercase letters

print("Enter Y/N:")

answer = input()
answer = answer.upper())

# While loop to check for the answer "Y"
# This loop will continue while the value of answer IS NOT "Y"
# Only when the user types "Y" will the loop exit and the program continue

while answer != "Y":
    print("I'm sorry, but you have to choose Y to continue!")
    print("Choose Y/N:")
    answer = input()
    answer = answer.upper())

print("Great, let's get started!")

# Letting the user choose which type of hero to create
print("Choose from the following hero options: ")
print("Press 1 for a Regular Superhero")
print("Press 2 for a Mutate Superhero")
print("Press 3 for a Robot Superhero")
answer2 = input()

if answer2=='1':

    # Creating the Superhero object
    hero = Superhero()

    # We print out the result of the created object, including its parameters
    print("You created a regular super hero!")
    print("Generating stats, name, and super powers.")

    # Creating dramatic effect

    for i in range(1):
        print("...........")
        time.sleep(3)

        print("(nah...you wouldn't like THAT one...)")

    for i in range(2):
        print("...........")
        time.sleep(3)

    print("(almost there....)")
    print(" ")
    print("Your name is %s." % (hero.superName))
    print("Your super power is: ", hero.power)
    print("Your new stats are:")
    print("")
    print("Brains: ", hero.brains)
    print("Braun: ", hero.braun)
    print("Stamina: ", hero.stamina)
    print("Wisdom: ", hero.wisdom)
    print("Constitution: ", hero.constitution)
    print("Dexterity: ", hero.dexterity)
    print("Speed ", hero.speed)
    print("")

elif answer2=='2':
        # Creating a Mutate object
        hero2 = Mutate()
        print("Generating stats, name, and super powers.")

    # Creating dramatic effect

        for i in range(1):
            print("...........")
            time.sleep(3)

            print("(nah...you wouldn't like THAT one...)")

        for i in range(2):
            print("...........")
            time.sleep(3)

        print("Your name is %s." % (hero2.superName))
        print("Your super power is: ", hero2.power)
        print("Your new stats are:")
        print("")
        print("Brains: ", hero2.brains)
        print("Braun: ", hero2.braun)
        print("Stamina: ", hero2.stamina)
        print("Wisdom: ", hero2.wisdom)
        print("Constitution: ", hero2.constitution)
        print("Dexterity: ", hero2.dexterity)
        print("Speed ", hero2.speed)
        print("")

elif answer2=='3':
        # Create a Robot character

        hero3 = Robot()

        print("Generating stats, name, and super powers.")

        # Creating dramatic effect

        for i in range(1):
            print("...........")
            time.sleep(3)

        print("(nah...you wouldn't like THAT one...)")

        for i in range(2):
            print("...........")
            time.sleep(3)

        print("Your name is %s." % (hero3.superName))
        print("Your super power is: ", hero3.power)
        print("Your new stats are:")
        print("")
        print("Brains: ", hero3.brains)
        print("Braun: ", hero3.braun)
        print("Stamina: ", hero3.stamina)
        print("Wisdom: ", hero3.wisdom)
        print("Constitution: ", hero3.constitution)
        print("Dexterity: ", hero3.dexterity)
        print("Speed ", hero3.speed) 

        print("")
else:
        print("You did not choose the proper answer! Program will now self-destruct!")

在这一集里!

在这一章中,我们取得了一些令人难以置信的飞跃,因为我们解决了在整本书中讨论的所有主题中最难掌握的概念。没错,相比之下,剩下的就一帆风顺了!

作为一个简短的提醒/未来备忘单,以下是我们在本章中所涉及的内容的总结:

  • OOP 代表面向对象编程。

  • 面向对象编程是一个概念,在这个概念中,我们练习创建可以在我们的程序中重用的代码。

  • 过程化编程包括编写代码,这些代码被设计成——在大多数情况下——逐行或以线性方式执行。

  • OOP 的核心围绕着类、对象和方法。

  • 一个类就像一个蓝图或模板。

  • 对象是一个类的实例。例如,如果一个类是一个家的蓝图,那么对象就是根据这个蓝图创建的实际的房子。

  • 类中使用的函数称为方法。

  • 要定义一个类,我们键入

    班级超级英雄:

    …一些代码…

  • def 语句用于定义类中的方法。例如:

    定义飞行:

    …密码…

  • init 用于初始化方法。

  • 当我们创建一个类的实例时,self 用来引用一个参数。

  • 我们通过将对象赋给变量来定义对象,如下所示:

    英雄=超级英雄()

  • 类本质上是分等级的;我们可以有一个主类(父类)和一个子类(子类)。

  • 子类继承父类或超类的方法和参数。

  • 要定义子类,可以使用如下代码:

    职业突变(超级英雄)*

九、其他数据结构简介

欢迎回来萌芽英雄!看起来你已经做了一整天的作业,家务,当然,还有打击犯罪。现在剩下要做的就是吃你的蔬菜,收拾好你的盘子,看在上帝的份上,去刷牙!

当然,你今晚可以一直快速刷牙,这可能会为你赢得一些时间,让你的程序员大脑拥有更多打击犯罪的能力!我是说,毕竟,当你可以给自己编一个程序来帮你咀嚼食物的时候,谁还需要牙齿呢?

不过说真的,去刷牙吧…

这本书现在已经读了一半,你已经为良好的编程实践和实用的语言技能打下了良好而坚实的基础,当你进入职场或独自开发自己的畅销软件时,你可以将这些知识带在身边。

当然,总有更多的东西需要学习。即使你读完这本编程知识的巨著,你的旅程也不会结束。做一名程序员就像做一名学生——你必须不断磨练自己的技能,学习最新最棒的技术。

除了语言更新之外(我们提到过计算机语言更新非常频繁),在某些时候你可能会想尝试其他编程语言和框架。然而,这是不久的将来的另一个篇章。

与此同时,这一章将回顾过去。我们之前讨论了数据结构,学习了如何使用变量和列表。虽然这些都是我们可以用来存储信息的强大工具,但它们并不是我们唯一可用的数据结构。

还有两个需要讨论的:元组字典。这将是这一集的话题。我们还将研究这两个存储单元的一些功能,并将它们整合到一些新程序中。

所以你知道该怎么做——不,不要用你的 x 光眼光去窥探本周数学考试的答案。

刷牙!

然后回到这里,准备学习如何像英雄一样编码。再来一些。

更多数据结构

如上所述,我们已经看到了两种数据结构:列表和变量。我们知道数据结构是保存数据或一条/多条信息的存储容器。我们可以在这些数据结构中存储信息,我们可以删除数据,我们可以向其中添加不同的数据。我们也可以取出数据,将其用于程序的一部分(比喻),然后放回原处(它实际上从未离开过容器)。

一个变量能够保存一段数据。这些数据可以是字母、数字或整数、字符串、句子、段落等等。此外,变量还可以保存列表等对象,这在技术上意味着它们可以保存“一个”以上的数据。同时,一个列表可以包含多条信息。把变量想象成一个文件夹,把列表想象成一个文件柜。

您可能还记得,为了定义变量,我们使用了如下代码:

a = "Hello"
b = 7
c = "Hello, I am being held prisoner in a variable!"

要定义一个列表,我们使用以下方法:

employees = [Big E.', 'Bloke Hogan', 'Alfredo the Butler']
priceList = ['5, 10, 20, 30, 40, 50]

如果我们想从一个变量中打印,我们应该按照下面这样写:

print(a)
print("You have this many apples: ", b)

您也可以使用格式化程序%s作为变量的替代。例如,假设你想写这样一句话:“你有 X 个苹果”,其中X是变量b的值。如果您键入了此代码:

print("You have %s apples!" , b)

运行它时,您会得到以下输出:

You have 7 apples!
To print a list, we can use:

print(employees)

或者打印列表中的单个项目,我们使用它的索引(记住:列表中的第一个项目位于索引0):

print(employees[1])

这将打印出:

Bloke Hogan

既然我们已经回顾了变量和列表,并且稍微刷新了一下关于数据结构如何工作的记忆,那么让我们继续学习 Python 必须提供的其他两种类型的数据结构。

什么是元组?

像列表和变量一样,元组也是一种数据结构。然而,与变量和列表不同,元组被认为是不可变的。这只是一种奇特的说法,即你不能以正常的方式改变它们的值或修改它们。

元组由的有序序列组成。这些项目(或值)在括号中定义,并用逗号分隔。要定义元组,可以使用如下代码:

villains = ('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')

就像列表一样,我们可以使用一个简单的 print()函数打印出元组的内容:

print(villains)

这将导致:

('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')

同样类似于列表,元组中的项目可以通过它们的index号来引用。元组中的项从索引 0 开始。因此,例如,如果我们想要打印我们的villains元组中的第一项,我们将使用:

print(villain[0])

这给了我们一个可怕的恶棍:

Eyebrow Raiser

如果我们想使用反派元组作为句子的一部分,有很多方法可以做到:

# Defining our tuple

villains = ('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')

# Printing the items in a tuple
print(villains)

# Printing single items in a tuple

print(villains[0])
print(villains[1])
print(villains[2])
print(villains[3])

# Ways to append tuple items to sentences

print("The first villain is the sinister", villains[0])
print("The second villain is the terrifying " + villains[1])

给了我们:

('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')
Eyebrow Raiser
Angry Heckler
Not So Happy Man

The Heck Raiser
The first villain is the sinister Eyebrow Raiser
The second villain is the terrifying Angry Heckler

我们使用元组中条目的另一种方式是通过切片它们。当您对一个元组进行切片时,您发出了您希望使用的值的范围。举个例子,这个的格式是villains[0:3]。如果我们运行这段代码:

print(villains[0:3])

输出将是:

('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man')

我知道你在想什么——索引3处的项目是'The Heck Raiser',那么为什么没有打印出来呢?

答案很简单:当我们切片时,冒号前的第一个数字告诉 Python 从哪里开始;后的数字冒号告诉它在该数字前结束*。*

如果我们要写print(villains[0:4]),只有在那时它才会打印出我们所有的四个项目,因为 Python 会在索引4中搜索项目——没有索引——并在它之前打印项目。

请注意,索引的起始编号不一定是 0。例如,如果我们想跳过打印元组中的第一项,我们可以只使用print(villains[1:4]),它将从第二项开始打印:

('Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')

我们可以用元组做的另一个技巧是将它们加在一起。例如,假设您有一个包含闪亮的紫色斗篷的元组和另一个充满圆点斗篷的元组。也许你厌倦了有太多装满斗篷的衣柜,所以你想把它们组合起来。如果是这样,你总是可以把你的元组连接在一起,形成一个全新的元组。考虑这个例子:

# Creating a tuple of my purple capes
purpleCapes = ('Purple Frilly Cape', 'Purple Short Cape', 'Purple Cape with Holes In It')
# Creating a tuple of my Polka Dot capes
polkaCapes = ('Black and White Polka Dot Cape', 'White and Beige Polka Dot Cape', 'Blue Polka Dot Cape Missing the Blue Polka Dots')

# Concatenating - or adding - my two tuples of capes together into a new tuple
allMyCapes = (purpleCapes + polkaCapes)

# Printing out the values of the newly created tuple
print(allMyCapes)

这段代码将元组purpleCapespolkaCapes中列出的条目组合在一起,并将它们存储在一个新创建的名为allMyCapes的元组中。如果您运行这段代码,您将得到:

('Purple Frilly Cape', 'Purple Short Cape', 'Purple Cape with Holes In It', 'Black and White Polka Dot Cape', 'White and Beige Polka Dot Cape', 'Blue Polka Dot Cape Missing the Blue Polka Dots')

注意,这不会改变或影响purpleCapespolkaCapes的值;请记住,您不能更改或修改元组中的值。

除了对元组使用+或串联运算符之外,还可以使用*或乘法运算符来重复存储在元组中的值:

print(allMyCapes[1] * 3)

这将打印出位于allMyCapes元组中索引1处的项目三次,结果是:

Purple Short CapePurple Short CapePurple Short Cape

注意,元组中列出的条目后面没有空格,所以当我们打印它们时,它们没有任何空格。

元组函数

就像列表一样,元组也有一组函数,可以用来与存储在其中的数据进行交互。然而,这些函数并不是元组独有的,可以在 Python 代码的其他地方使用。

两个大家比较熟悉的元组函数应该是min()max();你可能记得在前一章中使用过它们。当在一个元组中使用这两个函数时,它们执行它们通常的角色——也就是说,它们返回元组中的最小值和最大值项。

例如:

# Create a tuple containing a set of numbers
lowest_value = (1, 5, 10, 15, 20, 50, 100, 1000)

# Use the minimum function to return the lowest value item in the tuple
print(min(lowest_value))

该代码将返回:

1

因为从技术上讲,它是元组中最低的值。

如果我们想要最大的数字,我们将使用max()函数:

# Create a tuple containing a set of numbers
highest_value = (1, 5, 10, 15, 20, 50, 100, 1000)

# Use the maximum function to return the highest value item in the tuple
print(max(highest_value))

如你所料,它会返回:1000

另一个有用的元组函数是len(),您可能还记得,它返回字符串的长度或列表中元素的数量。当与元组一起使用时,它返回元组中包含的项数。

# Create a tuple with some items

super_hair = ('Super Stache', 'Macho Beard', 'Gargantuan Goat-tee', 'Villainous Toupee', 'Unfortunate Baldness')

# Print out the number of items in our tuple
print(len(super_hair))

这将返回 5,因为在我们的super_hair元组中总共有五个条目。

使用len()函数的例子包括这样的场景:你需要知道一家公司有多少员工,或者你在退休超级坏蛋的恶棍库里关了多少恶棍。如果您有一个包含这些邪恶角色名字的元组,您可以简单地对其使用len()函数,并快速计算人数。

当然,如果我们想快速查看有多少犯人,返回坏人金库中坏人的数量是有帮助的,但是如果我们想看到以某种顺序打印出来的列表呢——如果有这样的函数就好了……

哦,等等,有!

# A list of Villains Locked Away in the Villainous Vault of Bad Guys
villains = ('Naughty Man ', 'Skid Mark ', 'Mister Millenial ', 'Jack Hammer ', 'The Spelling Bee ', 'Drank All The Milk Man ', 'Wonder Wedgie ', 'Escape Goat')

# Print out a sorted list of our villains tuple

print(sorted(villains))

为了打印一个元组的排序列表(或者多个列表),我们使用了sorted()函数,如前面的代码所示。需要注意一些重要的事情。首先,按字母顺序返回排序结果。第二点——也是最重要的一点——sorted()函数只返回一个排序后的输出——它并不真正对元组中的数据进行排序。记住,元组是不可变的,不能被改变——即使是像sorted()这样强大的函数!

如果我们运行前面的代码,我们的结果将是:

['Drank All The Milk Man ', 'Escape Goat', 'Jack Hammer ', 'Mister Millenial ', 'Naughty Man ', 'Skid Mark ', 'The Spelling Bee ', 'Wonder Wedgie ']

当然,我们可以同样容易地对数字进行排序。考虑以下代码:

# A tuple of numbers we are going to sort
numbers_sort = (10, 20, 5, 2, 18)

# Sorting numbers in our tuple
print(sorted(numbers_sort))

如果我们运行它,它将返回输出:

[2, 5, 10, 18, 20]

当我们看到一个充满数字的元组时,让我们来看看另一个有用的函数——sum()。像到目前为止展示的其他函数一样,sum()也应该为您所熟悉。为了提醒您,它用于对数据结构中的数字求和。

下面是我们用来对一个元组中的项目总数求和的代码:

# A tuple of numbers we are going to sum
numbers_sum = (10, 20, 5, 2, 18)

# Summing items in a tuple
print(sum(numbers_sum))

运行这个程序可以得到numbers_sum元组中的项目总数:55

最后,我们还可以使用tuple()函数将其他数据结构——比如列表和变量——转换成一个元组:

# A list we will convert to a tuple
villainList = ['Naughty Man ', 'Skid Mark ', 'Mister Millenial ', 'Jack Hammer ', 'The Spelling Bee ', 'Drank All The Milk Man ', 'Wonder Wedgie ', 'Escape Goat']

# Using tuple() to convert villainList to a tuple

tuple(villainList)

# A string we will convert to a tuple
villain1 = "Mustached Menace!"
tuple(villain1)

元组更有趣

就在你以为我们和强大的元组的游戏结束了的时候,你发现你中了有奖游戏!在我们学习下一种数据结构之前,我们还需要学习一些东西。

在对元组的介绍中,我们了解到元组在一个非常重要的方面不同于列表:元组是不可变的,其中包含的数据不能以任何方式改变,而列表可以被操作、更新和添加。

如果您关心数据结构的数据完整性,这使得元组成为一个强大的工具。如果你有一组绝对不能改变的条目,那么将它们存储在一个元组中是最合适的。

也就是说,在某些情况下,你可能想从程序中删除一个元组。例如,也许你有一个元组来存储英雄和恶棍可能拥有的所有不同类型的面部毛发。如果这些面部装饰突然(但愿如此)过时了,会发生什么?为了确保元组中的项目不再被访问——并尽可能保持代码的整洁和高效——我们有两个选择。

首先,我们可以简单地用#或" ’ ’ "注释掉所有引用我们元组的代码。然而,这留下了这样的可能性,有人取消了对你的代码的注释,这可能导致错误或者——上帝保佑——胡须潮流的回归…哦不!

另一种选择是删除或修改引用元组的代码,然后实际删除元组本身。

有一种方法可以让我们删除整个元组;但是,我们不能删除元组中的项目。以下是删除元组的方法:

# A tuple full of facial hair styles for villains and heroes
facial_hair = ('Super Stache', 'Macho Beard', 'Gargantuan Goat-tee', 'Face Mullet',)

# Printing out facial hair
print(facial_hair)

# Using del to delete a tuple entirely
del facial_hair

# Printing out
print(facial_hair)

在这个代码片段中,我们首先创建了facial_hair元组,并给它分配了一堆项——其中一个可怕的项被称为' face mullet '(我甚至不知道这是什么意思)。

接下来,我们打印出facial_hair中的条目,以证明创建元组确实有效。在看到人们愿意在脸上生长的暴行列表后,我们决定最好删除facial_hair元组,假装它从未存在过。我们使用del语句来这样做,如下面的行所示:del facial_hair

最后,为了确保facial_hair真的被删除了,我们再打印一次。当我们运行这段代码时,关于输出会发生两件事。首先,打印出facial_hair中的项目。其次,我们收到一条错误消息。

为什么会出现信息错误?因为我们在第一次打印后就删除了facial_hair;当我们第二次去打印的时候,解释器就再也找不到了。这意味着我们成功地摆脱了世界上的疯狂facial_hair

只是英雄生活中的又一天!

如果运行该程序,您会看到以下结果:

('Super Stache', 'Macho Beard', 'Gargantuan Goat-tee', 'Face Mullet')
Traceback (most recent call last):
  File "C:/Users/James/AppData/Local/Programs/Python/Python36-32/TupleExamples.py", line 101, in <module>
    print(facial_hair)
NameError: name 'facial_hair' is not defined

有时当我们使用元组存储数据时,我们可能需要知道某个特定的项在我们的数据结构中出现了多少次。例如,单词“Mississippi”中有很多臭名昭著的 I。字母“s”也是如此。如果我们创建一个包含这个单词的元组,我们可以计算这个单词中同时出现“I”和“s”的次数,这样当人们要求我们告诉他们一些有趣的事情时,我们可以说,“你知道密西西比州有一堆 s 和 I 吗?真人真事,老弟!”

为了计算一个条目在元组中出现的次数,或者计算等于 s 的条目的数量,我们使用了count()方法。

# Tuple containing all of the letters used to spell Missisisippi
state = ('M', "i", "s", "s", "i", "s", "i", "s", "i", "p", "p", "i")
# Note: You could, technically, also easily create the tuple using state = tuple(‘Missisisippi’) with the tuple() command, which automatically converts a string into a tuple.
# Count the number of times "i" appears in our tuple and print out the result
print("There are this many of the letter i in Missisisippi: ")
print(state.count('i'))

# Count the number of times "s" appears in Missisisippi
print("There are this many of the letter s in Missisisippi: ")
print(state.count('s'))

代码state.count('i')中括号中的字符告诉 Python 计算‘I’在状态元组中出现的次数。

如果我们运行这个示例代码,我们将得到以下输出:

There are this many of the letter i in Missisisippi
5
There are this many of the letter s in Missisisippi
4

我们还可以使用关键字in在元组中搜索一个条目。该关键字主要询问值“x”是否是元组中的*😗

# Tuple containing all of the letters used to spell Missisisippi
state = ('M', "i", "s", "s", "i", "s", "i", "s", "i", "p", "p", "i")
# Checking to see if "z" or "i" appears in our state tuple
print('z' in state)
print('i' in state)

当检查一个条目是否包含在一个元组中时,in关键字返回一个布尔(真或假)响应。当我们运行这段代码时,它返回输出:

False
True

因为它首先检查在state元组中是否有一个'z',结果发现没有(False)。然后它在状态元组中检查一个'i',当然会找到一个或多个(True)。

元组示例

到目前为止,在本章中我们已经讨论了很多使用元组的方法,所以为了方便起见,下面你可以找到一个 Python 样本文件,其中包含了到目前为止在本章中编写的与元组相关的所有代码。

您可以随意修改这段代码,并查看更改已定义元组中的项目如何影响代码片段及其结果:

# Defining our tuple

villains = ('Eyebrow Raiser', 'Angry Heckler', 'Not So Happy Man', 'The Heck Raiser')

# Printing the items in a tuple
print(villains)

# Printing single items in a tuple

print(villains[0])
print(villains[1])
print(villains[2])
print(villains[3])

# Ways to append tuple items to sentences

print("The first villain is the sinister", villains[0])
print("The second villain is the terrifying " + villains[1])

# Slicing starting at index 0 and ending before the item at index 3
print(villains[0:3])

# Slicing starting at index 1 and ending before the item at index 4
print(villains[1:4])

# Creating a tuple of my purple capes
purpleCapes = ('Purple Frilly Cape', 'Purple Short Cape', 'Purple Cape with Holes In It')
# Creating a tuple of my Polka Dot capes
polkaCapes = ('Black and White Polka Dot Cape', 'White and Beige Polka Dot Cape', 'Blue Polka Dot Cape Missing the Blue Polka Dots')

# Concatenating - or adding - my two tuples of capes together into a new tuple
allMyCapes = (purpleCapes + polkaCapes)

# Printing out the values of the newly created tuple
print(allMyCapes)

# Print the item listed at index 1, 3 times
print(allMyCapes[1] * 3)

# Create a tuple containing a set of numbers
lowest_value = (1, 5, 10, 15, 20, 50, 100, 1000)

# Use the minimum function to return the lowest value item in the tuple
print(min(lowest_value))

# Create a tuple containing a set of numbers
highest_value = (1, 5, 10, 15, 20, 50, 100, 1000)

# Use the maximum function to return the highest value item in the tuple
print(max(highest_value))

# Create a tuple with some items

super_hair = ('Super Stache', 'Macho Beard', 'Gargantuan Goat-tee', 'Villainous Toupee', 'Unfortunate Baldness')

# Print out the number of items in our tuple
print(len(super_hair))

# A tuple of Villains Locked Away in the Villainous Vault of Bad Guys
villains = ('Naughty Man ', 'Skid Mark ', 'Mister Millenial ', 'Jack Hammer ', 'The Spelling Bee ', 'Drank All The Milk Man ', 'Wonder Wedgie ', 'Escape Goat')

# Print out a sorted list of our villains tuple

print(sorted(villains))

# A tuple of numbers we are going to sort
numbers_sort = (10, 20, 5, 2, 18)

# Sorting numbers in our tuple
print(sorted(numbers_sort))

# A tuple of numbers we are going to sum
numbers_sum = (10, 20, 5, 2, 18)

# Summing items in a tuple
print(sum(numbers_sum))

# A list we will convert to a tuple
villainList = ['Naughty Man ', 'Skid Mark ', 'Mister Millenial ', 'Jack Hammer ', 'The Spelling Bee ', 'Drank All The Milk Man ', 'Wonder Wedgie ', 'Escape Goat']

# Using tuple() to convert villainList to a tuple

tuple(villainList)

# A string we will convert to a tuple
villain1 = "Mustached Menace!"
tuple(villain1)

# A tuple full of facial hair styles for villains and heroes
facial_hair = ('Super Stache', 'Macho Beard', 'Gargantuan Goat-tee', 'Face Mullet',)

# Printing out facial hair
print(facial_hair)

# Using del to delete a tuple entirely
del facial_hair

# Printing out facial_hair to show that it is now empty
# print(facial_hair)

# Tuple containing all of the letters used to spell Missisisippi
state = ('M', "i", "s", "s", "i", "s", "i", "s", "i", "p", "p", "i")

# Count the number of times "i" appears in our tuple and print out the result
print("There are this many of the letter i in Missisisippi: ")
print(state.count('i'))

# Count the number of times "s" appears in Missisisippi
print("There are this many of the letter s in Missisisippi: ")
print(state.count('s'))

# Checking to see if "z" or "i" appears in our state tuple
print('z' in state)
print('i' in state)

# Looping through the previously created villainList tuple and printing out each item
for var in villainList:
    print(var)

使用字典

Python 有另一种数据结构,称为字典。字典与列表、变量和元组的区别非常有趣。尽管列表和元组的数据项存储在特定的索引中,因此可以在这些引用号处被引用(从索引 0 开始),但字典依赖于所谓的映射

映射是 Python 存储数据的一种方式,其中 Python 将keys映射到values。这就是所谓的键值对。

keys定义在密钥对值的左侧,通常与右侧的value相关或描述它们。Keys是不可变的,不能改变,而values是可变的,可以由任何数据类型组成。

要定义一个字典,您需要给它一个名称,然后将存储在字典中的数据用两个大括号{}括起来:

algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

在这种情况下,我们可以说algebro字典代表邪恶的恶棍,数学大师阿尔盖布罗!作为我们超级恶棍数据库的一部分,我们记录了所有不友好的邻居恶棍。在我们的字典中,我们有一些信息——即他们的代号、权力和真实姓名。我们在字典中通过命名我们的键来表示这些数据,以匹配它们将与之配对的数据。

因此,在这个例子中,例如,codename是一个键,Algebro是属于那个键的值。在我们的algebro字典中,它们将组成一个键值对。

algebro字典中的其他键值对是:

  • 权力:数学

  • 实名:艾尔。g .兄弟

如果我们想打印出字典,我们会使用:

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

# Print out the algebro dictionary
print(algebro)

产生的输出是:

{'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

字典中的键值对也可以称为元素或数据项,并且是未排序的。如您所料,它们也可以单独打印或调用。假设我们只想知道阿尔杰布罗的真名。要仅打印字典中特定键的值,我们应该编写:

print(algebro['real-name'])

Python 将返回结果:

Al. G. Bro.

字典方法

字典有几个内置的方法,我们可以用它们来与键和值进行交互。假设我们想看看字典中有哪些键。为了打印出来,我们将使用dict.keys()方法:

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

# Print just the keys in the algebro dictionary
print(algebro.keys())

运行时,我们得到的输出是:

dict_keys(['codename', 'power', 'real-name'])

如果我们只想访问algebro字典的值,我们将使用dict.values()方法,如下所示:

# Print just the values in the algebro dictionary
print(algebro.values())

给了我们:

dict_values(['Algebro', 'Mathemagics', 'Al. G. Bro.'])

但是如果我们想同时打印键和值呢?有一个方法也可以做到这一点,称为 dict.items()方法:

# Print the key-value pairs
print(algebro.items())

产量?

dict_items([('codename', 'Algebro'), ('power', 'Mathemagics'), ('real-name', 'Al. G. Bro.')])

当我们需要比较数据或查看字典中有哪些数据时,以这种方式使用字典方法非常有用。我们还可以将我们的关键字及其相关数据与其他字典进行比较。例如,恶棍阿尔杰布罗可能会出现在几本different字典中。一个可能存储了他的超能力和秘密身份的信息,而另一个字典可能包含他的高中记录和他在体育课上的成绩(相信我,数学魔术师阿尔杰布罗在高中体育课上很糟糕*!).*

*最后,还有一种方法可以打印出字典中的数据项——我们可以简单地迭代(或循环)字典,在每次迭代中打印出信息。还记得for循环吗?它在这里会派上用场:

# Using a for loop to iterate through and print out our dictionary

for key, value in algebro.items():
    print("The key is: ", key, " and the value is: ", value)

这个有用的代码片段会产生更加友好的输出:

The key is:  codename  and the value is:  Algebro
The key is:  power  and the value is:  Mathemagics
The key is:  real-name  and the value is:  Al. G. Bro.

字典带来更多乐趣

与元组不同,字典值——尽管不是键——可以修改。比方说,我们想给我们的阿尔杰布罗恶棍添加一个年龄。为此,我们可以简单地使用如下代码:

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}
# Add the key 'age' to the dictionary 'algebro' and assign it the value '42'
algebro['age'] = 42'

# Print out algebro to show the newly added key-value pair
print(algebro)

运行这段代码时,我们得到的结果是:

{'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.', 'age': '42'}

我们在这里可以看到,我们的新键值对'age''42'已经被添加。

这里你可能注意到的问题是age不是一个静态的数字;也就是说,它随时间而变化。每当我们的反派角色 Algebro 过生日时,我们都必须更新这个键值对。

不用担心,因为修改键值和添加新键值一样简单:

# Updating a the value for our 'age' key
algebro['age'] = 43

# Printing the algebro dictionary to see the updated value of the 'age' key
print(algebro)

现在,如果我们打印出age的值,它将等于:43

我们可以更新字典值的另一种方法是使用dict.update()方法。例如,我们也可以添加一个名为 villainType 的新键,并使用dict.update()方法给它一个成对的值mutate,如下所示:

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

# Using dict.update() to add a key-pair value to our 'algebro' dictionary
# Note the use of curly braces {}, mixed with parentheses ()
algebro.update({'villainType': 'mutate'})

# Printing out the results
print(algebro)

现在,如果您运行这段代码,输出将是:

{'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.', 'age': 43, 'villainType': 'mutate'}

注意添加了键-值对villainType mutate。另请注意,您还可以使用这个方法,使用相同的代码来更新字典中任何现有的键值对。

使用del关键字——我们以前见过——我们可以从字典中删除一个键值对。例如,如果出于某种原因,Algebro 失去了他的超能力,我们可以像这样删除整个键值对:

# Using the del keyword to delete a key-value pair
del algebro['power']

# Printing algebro to verify that we properly removed the key-value pair
print(algebro)

这给了我们:

{'codename': 'Algebro', 'real-name': 'Al. G. Bro.', 'age': 43, 'villainType': 'mutate'}

验证我们确实成功删除了键power及其相关值。

此外,如果我们想要删除整个字典,我们也可以使用del来删除:

# Deleting the algebro dictionary using the del keyword

del algebro

# Printing the deleted algebro, which results in an error
# This occurs because algebro no longer exists
print(algebro)

如果您运行该代码,您将得到一条错误消息,因为您现在正试图打印我们之前已经删除的algebro字典:

Traceback (most recent call last):
  File "C:/Users/James/AppData/Local/Programs/Python/Python36-32/DictionaryExamples.py", line 58, in <module>
    print(algebro)
NameError: name 'algebro' is not defined

最后,有时您可能希望删除字典中的所有条目或键值对,但是而不是删除字典本身。为此,我们使用 dict.clear()方法:

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

algebro.clear()
print(algebro)

如果您运行这段代码,您将得到以下输出:

{}

或者说,基本上就是一本空字典。或者,您可以通过简单地键入:algebra = {}来达到相同的效果。

其他词典方法

总的来说,大约有 26 种字典方法供你使用;篇幅不允许我在本书中涵盖所有这些问题;然而,我强烈建议你拓展自己的研究领域。尝试它们,明智地使用你新发现的能力!

这些方法中的一些已经在列表和元组中使用过;其中包括 sum()、min()、max()、sorted()等等。

这里有一个其他字典方法的列表:大胆尝试吧!

  • dict.clear():删除字典中的所有条目

  • dict.copy():返回字典的副本

  • dict.fromkeys():用于从序列中创建字典

  • 返回指定键的值

  • dict.items():返回给定字典的键/对值的视图

  • dict.keys():返回字典中的键

  • popitem():返回并删除一个字典元素

  • pop():返回并删除指定键中的元素

  • dict.setdefault():检查一个键是否存在,如果不存在,插入这个键(用一个值)

  • dict.values():返回字典中的所有值

  • dict.update():用于更新字典

您可以在字典上使用的其他方法包括:

  • any():测试 iterable 的元素是否为 True。

  • all():如果 iterable 的所有元素都为 True,则返回 True。

  • dict():用于创建字典。

  • enumerate():创建或返回一个枚举对象。

  • iter():返回给定对象的迭代器。

  • len():返回对象的长度。

  • max():返回最大的元素。

  • min():返回最小的元素。

  • sorted():返回一个排序列表。

  • sum():对所有项目求和。

示例字典代码

这是一个包含本章所有代码的样本文件。请随意对代码进行任何修改和实验(疯狂地)。注意任何错误,并尝试用有趣的方式修改它,利用你在书中学到的知识。

记住,玩得开心,有冒险精神(毕竟,不然怎么会是超级英雄呢?):

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

# Print out the algebro dictionary
print(algebro)

# Print out just the real-name key's value
print(algebro['real-name'])

# Print just the keys in the algebro dictionary
print(algebro.keys())

# Print just the values in the algebro dictionary
print(algebro.values())

# Print the key-value pairs
print(algebro.items())

# Using a for loop to iterate through and print out our dictionary

for key, value in algebro.items():
    print("The key is: ", key, " and the value is: ", value)

# Add the key 'age' to the dictionary 'algebro' and assign it the value '42'
algebro['age'] = '42'

# Print out algebro to show the newly added key-value pair
print(algebro)

# Updating a the value for our 'age' key

algebro['age'] = 43

# Printing the algebro dictionary to see the updated value of the 'age' key
print(algebro)

# Using dict.update() to add a key-pair value to our 'algebro' dictionary
# Note the use of curly braces {}, mixed with parentheses ()
algebro.update({'villainType': 'mutate'})

# Printing out the results
print(algebro)

# Using the del keyword to delete a key-value pair
del algebro['power']

# Printing algebro to verify that we properly removed the key-value pair
print(algebro)

########################################################
# This section of code is commented out because it will cause everything error
# Deleting the algebro dictionary using the del keyword
# del algebro

# Printing the deleted algebro, which results in an error
# This occurs because algebro no longer exists

#print(algebro)
################################################

# Create a dictionary name algebro and fill it with key-value pairs
algebro = {'codename': 'Algebro', 'power': 'Mathemagics', 'real-name': 'Al. G. Bro.'}

algebro.clear()
print(algebro)

在这一集里!

你应该为自己能走到这一步而感到骄傲!在这一集里,我们通过在你的记忆库中加入两种新的数据结构——元组和字典,扩展了你的大脑存储容量!

我们讲了很多,所以,像往常一样,用一个可爱的列表来总结我们在这一章中学到的大部分知识总是一个好主意。你猜怎么着?这是:

  • 除了变量和列表,元组和字典是另外两种保存信息的数据结构形式。

  • 元组类似于列表,只是元组是不可变的;也就是说,不能更改或修改它们的值。

  • 元组以这种方式定义:

    恶棍=(‘提眉者’,‘愤怒的质问者’,‘不太高兴的人’,‘见鬼的提眉者’)

  • 我们可以使用 print(恶棍)打印一个元组。

  • 我们使用:print(恶棍[0])打印元组中的一个条目,这将打印元组中的第一个条目——或者索引为 0 的条目。

  • 为了打印一个元组中的一系列项,我们使用:print(throughts[0:3]),它将打印位于索引 0、1 和 2 的项;它在位于第二个参数(本例中为 3)的项目之前结束打印。

  • 元组函数包括 min()、max()、len()、sorted()、sum()和 Tuple()。

  • del 关键字可用于删除整个元组。

  • count()计算元组中出现的实例数。

  • 我们可以使用in来检查某个东西是否出现在一个元组中;它返回一个布尔值真或假。

  • 字典使用映射来存储数据。

  • 字典包含一个键值对或一组键值对,也称为元素或数据项。

  • 键定义在冒号的左边,而值定义在右边。

  • 字典是这样定义的:

    algebro = {‘codename’: ‘Algebro ‘,’ power’: ‘Mathemagics ‘,’ real-name’: 'Al。哥哥。}

  • 您可以使用:print(algrebro)打印词典。

  • 您可以使用:print(algebro[‘real-name’])打印特定键的值。

  • 字典方法包括 dict.keys()、dict.items()和 dict.update()。

  • del 关键字也可以用来删除字典。

  • dict.clear()允许您从字典中清除元素,而不删除实际的字典(只是它的键和值对)。*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值