25

授業がよくわかりません。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

(元のコードパッド)

クラスのホワイトルームを返却したいです。これは、不可能であるか、正しく行われていないかのいずれかです。クラスを返す方法、または2つのクラスを「リンク」する方法を明確にして、他の部屋でホワイトルームが繰り返され、呼び出されたときに他の部屋(クラスになる)が返されるようにすることができれば、それは素晴らしいことです.

また、私は非常に不安定で__init__、その目的が何であるかはまだよくわかりません. 誰もが「初期化する」と言い続けていますが、それは確かにそうですが、それは私の脳を助けているようには見えません.

4

6 に答える 6

66

関数はクラスとは大きく異なります。関数を取り、 を に変更した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. ここにはグローバル変数以外にもより良いオプションがありますが、簡単にするために 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()

そして、これはクラスの基本的な紹介であり、それを状況に適用する方法です。

于 2012-04-04T04:58:34.427 に答える
5

聞いたことがあると思いますが、やってみます。

クラスは、一連の関数と変数を 1 つのオブジェクトにグループ化する方法です。突き詰めると、これは単に、すべてを意味のあるグループに編成する方法にすぎません。物事を理解しやすく、デバッグしやすくし、拡張し、維持しやすくすることには将来的に利点がありますが、基本的にはメンタル モデルで何かをより明確にするための方法にすぎません。

コードは、プログラム全体を「オブジェクト」内に記述しようとしているように見えます (実際には、関数が正しく記述されていません)。

代わりにこれを検討してください。

ドアとホワイトボードのある部屋のメンタル モデルを考えてみてください。ドアには色があります。また、ホワイトボードにはテキストを書き込むことができます。簡単にするためにそのままにしておきます。

私には、これは 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関数は、クラスの新しいインスタンスを「初期化」するときに呼び出されるものです。この例では、それぞれ Door と Whiteboard オブジェクトを内部で作成する 3 つの Room オブジェクトを作成しています。コンストラクターに渡すパラメーターは、 initRoom(parameter1, parameter2)関数に渡されます。これを使用して、ドアの色と、オプションでホワイトボード上のテキストを設定していることがわかります。また、オブジェクトに「属する」変数が参照されていることにも注意してください。この参照は、すべてのクラス関数に最初のパラメーターとして渡されるものです (後でクラスやその他のより高度なものを拡張するときに重要になります)。self

于 2012-04-04T04:36:32.970 に答える
2

MarkLutzによるPythonの学習からPythonのOOPSをよく理解しました。これは、Pythonの概念を理解し、特にPythonの方法をコーディングするための包括的な情報源です。

あなたのオンライン参照のために、私はこのサイトからのチュートリアルが好きです。この投稿を読んでください、それはinitであなたを助けます。PythonのOOPは、非常に理解しやすく、実装も簡単です。最初は気が遠くなるように見えますが、いくつかの基本的なOOPコードをプログラムした後は簡単です。学習をお楽しみください。

于 2012-04-04T04:44:31.210 に答える
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"

次に、ホワイトルームのような特定の部屋を次のように作成できます。

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

これは、クラスを使用して、スニペットを実際のゲームに変えるための私の最善の試みです。

于 2012-04-04T05:10:32.923 に答える
1

オブジェクト指向プログラミングは、最初は理解するのがとても楽しいものです。それを実際に理解する唯一の方法は、時間をかけて実際に多くのことを読んで練習することです。ここから始めるのがよいでしょう。http://www.voidspace.org.uk/python/articles/OOP.shtmlおよびhttp://wiki.python.org/moin/BeginnersGuide/Programmers

于 2012-04-04T04:22:29.157 に答える