Python-类和OOP基础 [英] Python - Classes and OOP Basics

查看:69
本文介绍了Python-类和OOP基础的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全理解课程.我已经阅读了python文档和其他一些教程.我了解了它的基本要点,但不了解细微差别.例如,在我的代码中:

I do not fully understand classes. I have read the python documentation and several other tutorials. I get the basic gist of it but don't understand the nuance. For instance in my code here:

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

(原始数字键盘)

我想回到班上的白厅.这是不可能的,或者是做不正确的.如果您可以弄清楚如何返回一个类或如何将两个类链接"在一起,以便在白色空间上重复其他空间,并且在调用时返回其他两个空间(这将是类),就太棒了.

I would like to return the class whiteroom. Which is, either not possible, or not being done correctly. If you could clear up how to return a class or how to "link" two classes together so that whiteroom repeats on the else and the other rooms (which would be classes) are returned when called that would be awesome.

我对__init__非常不满意,但仍然不确定它的目的是什么.每个人都不断告诉我它初始化"了,我敢肯定,但是这似乎并没有帮助我的大脑.

Also I'm super shaky on __init__ and am still not really sure what its purpose is. Everyone keeps telling me that it "initializes", which I'm sure it does, but that doesn't seem to be helping my brain out.

推荐答案

功能与类有很大不同.好像您已使用一个函数,只是将def更改为class.我想主要是在您的情况下有效,但这不是应该上课的方式.

Functions are very different from classes. It looks like you took a function and just changed the def to class. I guess that mostly works in your case, but it's not how classes are supposed to go.

类包含函数(方法)和数据.例如,您有一个球:

Classes contain functions (methods) and data. For example, you have a ball:

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类.我们如何使用它?

Now we have a Ball class. How can we use it?

>>> ball1 = Ball()
>>> ball1
<Ball object at ...>

它看起来不是很有用.数据是有用的地方:

It doesn't look very useful. The data is where it could be useful:

>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)

好的,很酷,但是与全局变量相比有什么优势?如果您还有另一个Ball实例,它将保持独立:

Alright, cool, but what's the advantage over a global variable? If you have another Ball instance, it will remain independent:

>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)

ball1仍然独立:

>>> ball1.velocity
(0, 0)

现在我们定义的bounce方法(类中的函数)怎么办?

Now what about that bounce method (function in a class) we defined?

>>> ball2.bounce()
>>> ball2.velocity
(5, -10)

bounce方法使它修改了自身的velocity数据.同样,ball1没有被触及:

The bounce method caused it to modify the velocity data of itself. Again, ball1 was not touched:

>>> ball1.velocity

应用程序

一个球很整齐,但是大多数人并没有模仿它.您正在制作游戏.让我们考虑一下我们拥有什么样的东西:

Application

A ball is neat and all, but most people aren't simulating that. You're making a game. Let's think of what kinds of things we have:

  • 房间是我们最明显的东西.
  • A room is the most obvious thing we could have.

所以我们来腾个房间.房间有名称,因此我们将存储一些数据:

So let's make a room. Rooms have names, so we'll have some data to store that:

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'

虚张声势.但是,如果您希望不同的房间具有不同的功能,那么这并不是那么有用,所以让我们创建一个 subclass . 子类从其超类继承所有功能,但是您可以添加更多功能或覆盖超类的功能.

Spiffy. This turns out not to be all that useful if you want different rooms to have different functionality, though, so let's make a subclass. A subclass inherits all functionality from its superclass, but you can add more functionality or override the superclass's functionality.

让我们考虑一下我们要如何处理房间:

Let's think about what we want to do with rooms:

我们想与房间互动.

We want to interact with rooms.

那我们该怎么做?

用户键入一行得到响应的文本.

The user types in a line of text that gets responded to.

它的响应方式取决于房间,所以让我们使用称为interact的方法来处理房间:

How it's responded do depends on the room, so let's make the room handle that with a method called 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!"

现在让我们尝试与之交互:

Now let's try interacting with it:

>>> 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 我们还要创建一个红色房间.

Your original example featured moving between rooms. Let's use a global variable called current_room to track which room we're in.1 Let's also make a red room.

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添加代码,使您可以回到红色的房间.

Exercise for the reader: Add code to WhiteRoom's interact that allows you to go back to the red room.

现在我们可以正常工作了,让我们将它们放在一起.使用所有房间上的新name数据,我们还可以在提示中显示当前房间!

Now that we have everything working, let's put it all together. With our new name data on all rooms, we can also show the current room in the prompt!

def play_game():
    global current_room
    while True:
        line = raw_input(current_room.name + '> ')
        current_room.interact(line)

您可能还想创建一个功能来重置游戏:

You might also want to make a function to reset the game:

def reset_game():
    global current_room, white_room, red_room
    white_room = WhiteRoom()
    red_room = RedRoom()
    current_room = white_room

将所有的类定义和这些函数放到一个文件中,您可以在这样的提示下播放它(假设它们在mygame.py中):

Put all of the class definitions and these functions into a file and you can play it at the prompt like this (assuming they're in 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脚本就可以玩游戏,您可以在底部添加以下内容:

To be able to play the game just by running the Python script, you can add this at the bottom:

def main():
    reset_game()
    play_game()

if __name__ == '__main__':  # If we're running as a script...
    main()

这是对类以及如何将其应用于您的情况的基本介绍.

And that's a basic introduction to classes and how to apply it to your situation.

这篇关于Python-类和OOP基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆