我没有完全理解课程。我已经阅读了python文档和其他一些教程。我了解了它的基本要点,但不了解细微差别。例如在我的代码中:
class whiteroom():
""" Pick a door: red, blue, green, or black. """
do = raw_input("> ")
if "red" in do:
print "You entered the red room."
elif "blue" in do:
print "You entered the blue room."
elif "green" in do:
print "You entered the green room."
elif "black" in do:
print "You entered the black room."
else:
print "You sit patiently but slowly begin to stave. You're running out of time."
return whiteroom()
game = whiteroom()
game
(原始codepad)
我想回到教室的白色房间。这是不可能的,或者是做不正确的。如果您可以弄清楚如何返回一个类,或如何将两个类“链接”在一起,以便在白纸上重复白色空间,并且在调用时返回其他两个空间(即类),那将是很棒的。
另外,我对__init__
非常不满意,仍然不确定其目的是什么。每个人都不断告诉我它“初始化”了,我敢肯定的是,但是这似乎并没有帮助我的大脑。
python大神给出的解决方案
函数与类有很大的不同。好像您已使用一个函数,只是将def
更改为class
。我猜这在您的情况下最有效,但并不是应该上课的方式。
类包含函数(方法)和数据。例如,您有一个球:
class Ball(object):
# __init__ is a special method called whenever you try to make
# an instance of a class. As you heard, it initializes the object.
# Here, we'll initialize some of the data.
def __init__(self):
# Let's add some data to the [instance of the] class.
self.position = (100, 100)
self.velocity = (0, 0)
# We can also add our own functions. When our ball bounces,
# its vertical velocity will be negated. (no gravity here!)
def bounce(self):
self.velocity = (self.velocity[0], -self.velocity[1])
现在我们有一个Ball
类。我们如何使用它?
>>> ball1 = Ball()
>>> ball1
<Ball object at ...>
它看起来不是很有用。数据是有用的地方:
>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)
好吧,很酷,但是与全局变量相比有什么优势?如果您还有另一个Ball
实例,它将保持独立:
>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)
并且ball1
保持独立:
>>> ball1.velocity
(0, 0)
现在,我们定义的那个bounce
方法(类中的函数)呢?
>>> ball2.bounce()
>>> ball2.velocity
(5, -10)
bounce
方法使它修改自身的velocity
数据。同样,ball1
没有被触及:
>>> ball1.velocity
应用
球很齐整,但是大多数人并没有模仿它。您正在制作游戏。让我们考虑一下我们拥有什么样的东西:
房间是我们可以拥有的最明显的东西。
因此,让我们腾出空间。房间有名称,因此我们将有一些数据来存储:
class Room(object):
# Note that we're taking an argument besides self, here.
def __init__(self, name):
self.name = name # Set the room's name to the name we got.
让我们做一个实例:
>>> white_room = Room("White Room")
>>> white_room.name
'White Room'
随便但是,如果您希望不同的房间具有不同的功能,那么这并不是那么有用,所以让我们创建一个子类。子类从其超类继承所有功能,但是您可以添加更多功能或覆盖超类的功能。
让我们考虑一下我们想对房间做什么:
我们想与房间互动。
我们该怎么做?
用户键入一行得到响应的文本。
它的响应方式取决于房间,所以让我们使用称为interact
的方法来处理房间:
class WhiteRoom(Room): # A white room is a kind of room.
def __init__(self):
# All white rooms have names of 'White Room'.
self.name = 'White Room'
def interact(self, line):
if 'test' in line:
print "'Test' to you, too!"
现在,让我们尝试与之交互:
>>> white_room = WhiteRoom() # WhiteRoom's __init__ doesn't take an argument (even though its superclass's __init__ does; we overrode the superclass's __init__)
>>> white_room.interact('test')
'Test' to you, too!
您最初的示例是在房间之间移动。让我们使用一个名为current_room
的全局变量来跟踪我们所在的房间。1我们还创建一个红色房间。
1.除了全局变量外,这里还有更好的选择,但是为了简单起见,我将使用一个。
class RedRoom(Room): # A red room is also a kind of room.
def __init__(self):
self.name = 'Red Room'
def interact(self, line):
global current_room, white_room
if 'white' in line:
# We could create a new WhiteRoom, but then it
# would lose its data (if it had any) after moving
# out of it and into it again.
current_room = white_room
现在让我们尝试一下:
>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'
读者的练习:在WhiteRoom
的interact
中添加代码,使您可以回到红色的房间。
现在我们已经完成所有工作,下面将它们放在一起。使用所有房间的新name
数据,我们还可以在提示中显示当前房间!
def play_game():
global current_room
while True:
line = raw_input(current_room.name + '> ')
current_room.interact(line)
您可能还想创建一个函数来重置游戏:
def reset_game():
global current_room, white_room, red_room
white_room = WhiteRoom()
red_room = RedRoom()
current_room = white_room
将所有的类定义和这些函数放入文件中,您可以在这样的提示下播放它(假设它们在mygame.py
中):
>>> import mygame
>>> mygame.reset_game()
>>> mygame.play_game()
White Room> test
'Test' to you, too!
White Room> go to red room
Red Room> go to white room
White Room>
为了仅通过运行Python脚本即可玩游戏,您可以在底部添加以下代码:
def main():
reset_game()
play_game()
if __name__ == '__main__': # If we're running as a script...
main()
这是对类以及如何将其应用于您的情况的基本介绍。
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
Spacy如何将标记标签整体化? - python在包含#标签(例如tweet)的句子中,spacy的令牌生成器将标签分为两个令牌:import spacy nlp = spacy.load('en') doc = nlp(u'This is a #sentence.') [t for t in doc] 输出:[This, is, a, #, sentence, .…
Python集合模块中的defaultdict是否真的比使用setdefault更快? - python我见过其他Python程序员在以下用例中使用collections模块中的defaultdict:from collections import defaultdict s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue'…
re.findall不返回全场比赛吗? - python我有一个包含一堆字符串的文件,例如“ size = XXX;”。我第一次尝试使用python的re模块,并且对以下行为感到有些困惑:如果我在正则表达式中使用管道作为“或”,我只会看到返回的匹配项。例如。:>>> myfile = open('testfile.txt','r').read() >…
Python numpy数据指针地址无需更改即可更改 - python编辑经过一些摆弄之后,到目前为止,我已经隔离了以下状态:一维数组在直接输入变量时提供两个不同的地址,而在使用print()时仅提供一个地址2D数组(或矩阵)在直接输入变量时提供三个不同的地址,在使用print()时提供两个地址3D数组在直接输入变量时提供两个不同的地址,而在使用print()时仅给出一个(显然与一维数组相同)像这样:>>> …