Python - 类和 OOP 基础

标签 python oop

我不完全理解类。我已经阅读了 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 在 else 上重复,并且在调用时返回其他房间(将是类),那就太棒了。

另外我在 __init__ 上非常不稳定我仍然不确定它的目的是什么。每个人都一直告诉我它“初始化”了,我确信它确实如此,但这似乎并没有帮助我的大脑。

最佳答案

函数与类非常不同。看起来你拿了一个函数,只是改变了 defclass .我想这主要适用于您的情况,但这不是类(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类(class)。我们如何使用它?
>>> 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'
    

    漂亮。但是,如果您希望不同的房间具有不同的功能,那么这并不是很有用,所以让我们创建一个子类。子类从其父类(super class)继承所有功能,但您可以添加更多功能或覆盖父类(super class)的功能。

    让我们想想我们想用房间做什么:

    我们想与房间互动。

    我们如何做到这一点?

    用户输入一行得到响应的文本。

    它的响应方式取决于房间,所以让我们使用名为 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'
    

    读者练习:将代码添加到 WhiteRoominteract这让你可以回到红色房间。

    现在我们已经一切正常了,让我们把它们放在一起。随着我们的新 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 - 类和 OOP 基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004850/

    相关文章:

    python - Jupyter 上的 TensorFlow : Can't restore variables

    python - 无法从 Python 中的 Appkit 导入 NSWorkspace

    oop - 是否有常用的 OO 模式来保存 "constant variables"?

    java - 构造不可变对象(immutable对象)的抽象生成器

    c++ - 如果未满足某些条件,从方法返回什么?

    NodeJS 中的 JavaScript OOP : how?

    python - pandas 数据框,将 index_col 设置为我的 csv 名称

    python - 在 Django View 中的 render() 中发送图像作为参数

    python - 基于 Spacy token 的匹配, token 之间的 token 数量为 'n'

    c++ - 帮助解决这个问题(指针和多态性)