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

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

问题描述

我不完全理解类.我已经阅读了 python 文档和其他几个教程.我明白了它的基本要点,但不明白其中的细微差别.例如在我这里的代码中:

class whiteroom():"""选择一扇门:红色、蓝色、绿色或黑色."""do = raw_input(">")如果红色"在做:打印 "你进入了红色房间."elif蓝色"在做:打印 "你进入了蓝色房间."elif绿色"在做:打印您进入了绿色房间."elif黑色"在做:打印你进入了黑屋."别的:打印你耐心地坐着,但慢慢地开始了.你的时间不多了."返回白屋()游戏 = 白屋()游戏

(原codepad)

我想归还教室的白色房间.这是不可能的,或者没有正确完成.如果您能弄清楚如何返回一个类或如何将两个类链接"在一起,以便 whiteroom 在 else 上重复,而其他房间(将是类)在调用时返回,那就太棒了.

此外,我对 __init__ 非常不稳定,仍然不确定它的目的是什么.每个人都一直告诉我它初始化"了,我敢肯定它确实如此,但这似乎并没有帮助我解决问题.

解决方案

函数与类非常不同.看起来您使用了一个函数,只是将 def 更改为 class.我猜大部分适用于您的情况,但这不是课程应该如何进行.

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

class Ball(object):# __init__ 是一个特殊的方法,每当你尝试制作# 一个类的实例.正如您所听到的,它初始化对象.# 在这里,我们将初始化一些数据.def __init__(self):# 让我们向 [instance of the] 类添加一些数据.self.position = (100, 100)self.velocity = (0, 0)# 我们也可以添加我们自己的函数.当我们的球反弹时,# 它的垂直速度将被否定.(这里没有重力!)def反弹(自我):self.velocity = (self.velocity[0], -self.velocity[1])

现在我们有一个 Ball 类.我们如何使用它?

<预><代码>>>>球 1 = 球()>>>球1<球对象在...>

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

<预><代码>>>>ball1.position(100, 100)>>>球1.速度(0, 0)>>>ball1.position = (200, 100)>>>ball1.position(200, 100)

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

<预><代码>>>>球2 = 球()>>>ball2.velocity = (5, 10)>>>ball2.position(100, 100)>>>ball2.velocity(5, 10)

并且 ball1 保持独立:

<预><代码>>>>球1.速度(0, 0)

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

<预><代码>>>>ball2.bounce()>>>ball2.velocity(5, -10)

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

<预><代码>>>>球1.速度

申请

球很整洁,但大多数人并没有模仿它.你在做游戏.让我们想想我们有什么样的东西:

  • 房间是我们可以拥有的最明显的东西.

所以让我们开一个房间.房间有名字,所以我们会有一些数据来存储:

class Room(object):# 请注意,我们在这里接受了除 self 之外的参数.def __init__(self, name):self.name = name # 将房间的名称设置为我们得到的名称.

让我们做一个实例:

<预><代码>>>>white_room = Room("白色房间")>>>white_room.name《白色房间》

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

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

我们想与房间互动.

我们该怎么做?

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

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

class WhiteRoom(Room): # 白色房间是一种房间.def __init__(self):# 所有白色房间的名称都为白色房间".self.name = '白色房间'def 交互(自我,行):如果测试"在线:也打印'测试'给你!"

现在让我们尝试与它互动:

<预><代码>>>>white_room = WhiteRoom() # WhiteRoom 的 __init__ 不带参数(即使它的超类的 __init__ 带参数;我们覆盖了超类的 __init__)>>>white_room.interact('测试')也给你测试"!

您最初的示例是在房间之间移动.让我们使用一个名为 current_room 的全局变量来跟踪我们在哪个房间.1让我们也制作一个红色房间.

1.除了全局变量,这里还有更好的选择,但为了简单起见,我将使用一个.

class RedRoom(Room): # 红色房间也是房间的一种.def __init__(self):self.name = '红色房间'def 交互(自我,行):全局 current_room,white_room如果 'white' 在线:# 我们可以创建一个新的 WhiteRoom,然后它# 移动后会丢失数据(如果有的话)# 退出并再次进入.current_room = white_room

现在让我们试试:

<预><代码>>>>red_room = RedRoom()>>>current_room = red_room>>>current_room.name《红房》>>>current_room.interact('去白房间')>>>current_room.name《白色房间》

读者练习:将代码添加到 WhiteRoominteract 中,让您可以返回红色房间.

现在我们已经一切正常了,让我们把它们放在一起.有了所有房间的新 name 数据,我们还可以在提示中显示当前房间!

def play_game():全局 current_room而真:line = raw_input(current_room.name + '> ')current_room.interact(行)

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

def reset_game():全局 current_room、white_room、red_roomwhite_room = WhiteRoom()red_room = RedRoom()current_room = white_room

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

<预><代码>>>>导入我的游戏>>>mygame.reset_game()>>>mygame.play_game()白色房间>测试也给你测试"!白色房间>去红房间红色房间>去白色房间白色房间>

为了能够通过运行 Python 脚本来玩游戏,您可以在底部添加:

def main():重置游戏()玩游戏()if __name__ == '__main__': # 如果我们作为脚本运行...主要的()

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

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

(original codepad)

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.

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.

解决方案

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])

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)

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)

And ball1 remains independent:

>>> ball1.velocity
(0, 0)

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

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

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.

And let's make an instance of it:

>>> white_room = Room("White Room")
>>> white_room.name
'White Room'

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.

And how do we do that?

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

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!

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. There's better options besides global variables here, but I'm going to use one for simplicity.

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

Now let's try that:

>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'

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

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

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>

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天全站免登陆