'Python - Classes and OOP Basics
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.
Solution 1:[1]
I'm sure you've heard all this before, but I'll give it a go.
Classes are a way to group up a bunch of function and variables into a single object. When you get all the way down to it, this is simply a way of organizing everything into groups that make sense. There are benefits down the road for making things easier to understand, debug, extend, or maintain, but basically its just a way to make something more defined in your mental model.
Your code looks like you are trying to write your entire program inside an 'object' (really, you just have an incorrectly written function).
Consider this instead.
Think of your mental model of rooms which have doors to them and whiteboards in them. Doors have a color. Also, whiteboards can have some text written on them. We'll leave it there to be simple.
To me, this suggests 3 different objects -- a door object that has a string for color, a whiteboard object that has a string for the text, and a room object that has a door and a whiteboard.
Consider the following code:
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
The init function is what gets called when you 'initialize' a new instance of your class. In the example I am making 3 Room objects which each create a Door and Whiteboard object internally. The parameters I pass into the constructor Room(parameter1, parameter2) get passed to the init functions - you can see I'm using this to set the door color and optionally some text on the whiteboard. Also notice that the variables that 'belong' to the objects are referenced with self - this reference is what gets passed in as the first parameter to all class functions (and becomes more important later when you are extending classes and other more advanced things).
Solution 2:[2]
You're really far off.
Sorry to say it, but this is just barely salvageable.
From what I can tell you want something like a room class, for instance:
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"
Then you can make a specific room like the whiteroom like so:
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."
Then you'd have do this to run the game:
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()
That's my best attempt at turning your snippet into an actual game, using classes.
Solution 3:[3]
class Circle():
pi = 3.14
def __init__(self,radius=1):
self.radius = radius
self.area = radius*radius*self.pi
def get_circrumference(self):
return self.radius* self.pi*2
result: Circle(23)
my_circle = Circle(30)
my_circle.pi = 3.14
my_circle.radius = 30
my_circle.get_circrumference() = 118.4
my_circle.area = 2826.0
help(Circle) = Help on class Circle in module main:
class Circle(builtins.object)
| Circle(radius=1)
|
| Methods defined here:
|
| init(self, radius=1)
| Initialize self. See help(type(self)) for accurate signature.
|
| get_circrumference(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| dict
| dictionary for instance variables (if defined)
|
| weakref
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| pi = 3.14
Solution 4:[4]
Here's a simple implementation of cartesian points using class:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, move_x, move_y):
self.x += move_x
self.y += move_y
def scale(self, factor):
self.x *= factor
self.y *= factor
def mod(self):
return (self.x ** 2 + self.y ** 2) ** (1 / 2)
A = Point(3, 4)
print(A.x, A.y) -> 3 4
print(A.mod()) -> 5
A.move(2, 8) #(5, 12)
A.scale(2) #(10, 26)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Collin Green |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Shub |
