我不完全理解课程。我已经阅读了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)
我想返回班级whiteroom。这是不可能的,或者没有正确完成。如果您可以清理如何返回一个类或如何将两个类“链接”在一起,以便在其他地方重复使用whiteroom,并且在调用时返回其他房间(可能是类)。
我__init__
也非常不稳定,我仍然不确定它的目的是什么。每个人都在告诉我它“初始化”,我确信它确实如此,但这似乎并没有帮助我的大脑。
答案 0 :(得分:44)
功能与类非常不同。看起来您已经执行了一项功能,只是将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
的{{1}},以便您返回红色房间。
现在我们已经完成了所有工作,让我们把它们放在一起。通过我们在所有房间的新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
为了能够通过运行Python脚本来玩游戏,您可以在底部添加:
>>> 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>
这是对课程的基本介绍以及如何将其应用到您的情境中。
答案 1 :(得分:5)
我相信你以前听过这一切,但我会试一试。
类是一组将一堆函数和变量组合到一个对象中的方法。当你完全了解它时,这只是一种将所有内容组织成有意义的组的方法。为了使事情更容易理解,调试,扩展或维护,有一些好处,但基本上它只是一种在心理模型中做出更多定义的方法。
您的代码看起来像是在尝试将整个程序写入“对象”(实际上,您只是编写了错误的函数)。
请考虑这一点。
想想你的房间的心理模型,房间有门,白板在里面。门有颜色。此外,白板上可以写一些文字。我们会把它留在那里简单。
对我来说,这表明了3个不同的对象 - 一个门对象,它有一个颜色的字符串,一个白板对象,有一个字符串用于文本,还有一个房间对象,有一个门和一个白板。
请考虑以下代码:
class Door(object):
def __init__(self, color):
self.color = color
class Whiteboard(object):
def __init__(self, default_text=''):
self.text = ''
self.write_text(default_text)
def write_text(self, text):
self.text += text
def erase(self):
self.text = ''
class Room(object):
def __init__(self, doorcolor, whiteboardtext=''):
self.whiteboard = Whiteboard(whiteboardtext)
self.door = Door(doorcolor)
# make a room with a red door and no text on the whiteboard
room1 = Room('red')
# make a room with a blue door and 'yeah, whiteboard' on the whiteboard
room2 = Room('blue', 'yeah, whiteboard')
# make a room with a green door
room3 = Room('green')
# now I can play around with my 'rooms' and they keep track of everything internally
print 'room 1 door color: ' + room1.door.color
print 'room 2 door color: ' + room2.door.color
# all my rooms have a door and a whiteboard, but each one is different and self contained. For example
# if I write on room 1's whiteboard, it doesn't change anything about room 3s
print 'room1 whiteboard: ' + room1.whiteboard.text
print 'room2 whiteboard: ' + room2.whiteboard.text
print 'room3 whiteboard: ' + room3.whiteboard.text
print '-- changeing room 1 whiteboard text --'
room1.whiteboard.write_text('oop is really helpful')
print 'room1 whiteboard: ' + room1.whiteboard.text
print 'room2 whiteboard: ' + room2.whiteboard.text
print 'room3 whiteboard: ' + room3.whiteboard.text
init 函数是在初始化类的新实例时调用的函数。在示例中,我正在制作3个Room对象,每个对象在内部创建一个Door和Whiteboard对象。我传递给构造函数Room(parameter1, parameter2)
的参数传递给 init 函数 - 你可以看到我正在使用它来设置门颜色和白板上的一些文本。还要注意“{属于”对象的变量是用self
引用的 - 这个引用作为第一个参数传递给所有类函数(后来在扩展类和其他更多时变得更加重要)高级的东西)。
答案 2 :(得分:2)
我从Learning Python by Mark Lutz了解了Python中的OOPS。它是理解Python概念的综合资源,尤其是对 Pythonic 方式进行编码。
对于您的在线参考,我喜欢this网站上的教程。 通过这个post,它将帮助您使用init。 Python中的OOP非常易于理解和实现。一开始看起来令人生畏,但在编写一些基本的OOP代码之后,这是一件轻而易举的事。 享受学习..
答案 3 :(得分:2)
你真的很远。
很抱歉这么说,但这只是勉强可以挽救。
据我所知,你想要像房间类这样的东西,例如:
class Room(object):
''' A generic room '''
def __init__(self):
self.choices = None
self.enter()
def enter(self):
''' Enter the room, to be filled out in subclass '''
pass
def print_choices(self):
'''You are stuck bro'''
print "You are stuck bro"
然后你就可以像whiteroom那样建造一个特定的房间:
class Whiteroom(Room):
''' A white room '''
def __init__(self):
self.choices = ["red", "blue", "green", "black"]
self.enter()
def enter(self):
print "You sit patiently, but slowly begin to starve. You're running out of time."
def print_choices(self):
print "You can choose from the following rooms:"
print self.choices
class Blackroom(Room):
''' A black room '''
def enter(self):
print "It's really dark in here. You're out of time."
class Redroom(Room):
''' A red room '''
def __init__(self):
self.choices = ["black", "blue", "green", "white"]
self.enter()
def enter(self):
print "It's getting hot in here. So take off all your clothes."
def print_choices(self):
print "You can choose from the following rooms:"
print self.choices
class Blueroom(Room):
''' A blue room '''
def __init__(self):
self.choices = ["black", "red", "green", "white"]
self.enter()
def enter(self):
print "It's nice and cool in here. Stay awhile if you want."
def print_choices(self):
print "You can choose from the following rooms:"
print self.choices
class Greenroom(Room):
''' A green room '''
def __init__(self):
self.choices = ["black", "red", "blue", "white"]
self.enter()
def enter(self):
print "You won."
然后你就可以这样做来运行游戏:
print "Type 'quit' to quit"
print "Type 'choices' to see what your choices are"
current_room = Whiteroom()
done = False
while (not done):
entry = raw_input("> ")
if entry == "quit":
done = True
if "choices" in entry:
current_room.print_choices()
if current_room.choices:
if entry in current_room.choices:
if "white" in entry:
current_room = Whiteroom()
if "black" in entry:
current_room = Blackroom()
if "red" in entry:
current_room = Redroom()
if "green" in entry:
current_room = Greenroom()
done = True
if "blue" in entry:
current_room = Blueroom()
这是我使用课程将你的片段变成实际游戏的最佳尝试。
答案 4 :(得分:1)
面向对象编程首先要掌握一个非常有趣的事情,真正散列它的唯一方法是实际花时间做大量的阅读和练习。一个好的开始就在这里。 http://www.voidspace.org.uk/python/articles/OOP.shtml和http://wiki.python.org/moin/BeginnersGuide/Programmers