Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7740475
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T08:47:17+00:00 2026-06-01T08:47:17+00:00

I do not fully understand classes. I have read the python documentation and several

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T08:47:18+00:00Added an answer on June 1, 2026 at 8:47 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have read the document already but i do not fully understand The default
i've read the cookies tutorial on w3schools BUT i do not fully understand it
Please not that I fully understand this is a dumb ass idea, but its
I've read Visual VM remotely over ssh but I think I've not fully understood
I am getting a successful response back, but I do not fully understand how
i do not fully understand how to communicate between adobe air (using flex3) and
I am getting a warning I do not fully understand every time I run
Not sure I fully understand what phpmyadmin does. I created a database in phpmyadmin,
Not that it matters strictly, and maybe I just don't yet fully understand how
Possible Duplicate: What are the reasons why Map.get(Object key) is not (fully) generic According

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.