Reputation: 123
Can someone please explain why my enter method in the following class is returning two values? I'm learning python and in the process of creating a simple game to grasp OOP and classes. Anyhow I need the enter method to return a random snippet from the snippets list. But I keep getting two snippets instead of one. Can someone explain why?
from sys import exit
from random import randint
class Island(object):
def enter(self):
pass
class Loser(Island):
snippets = ["Welcome to loser Island",
"Can't win them all",
"There's always next time"]
def enter(self):
print Loser.snippets[randint(0,len(self.snippets)-1)]
loser_test = Loser()
loser_test.enter()
Upvotes: 0
Views: 60
Reputation: 49330
Generally, you'll create a class and then describe the behavior and contents of an instance of that class. An instance of a class is an object whose type is that class. For example, john = Person('John', 'Doe')
would create a Person
object, sending 'John'
and 'Doe'
to the object's __init__
method (a constructor).
The following sticks to instances of a class by making use of the word self
. self
is not a keyword (like in
); it's just the word that an object's description uses to refer to the object itself. You can use any word (like xyz
in for xyz in [1,2,3]
), but self
is preferred.
>>> import random
>>> class L(object):
... def __init__(self):
... self.snippets = ["Welcome", "Can't", "There's"]
... def enter(self):
... print (random.choice(self.snippets))
...
>>> l = L()
>>> l.enter()
There's
>>> l.enter()
There's
>>> l.enter()
Welcome
>>> l.enter()
Can't
>>>
Upvotes: 1
Reputation: 114038
Im going to take a guess and say its because you have something like this
class Island:
def __init__(self):
print self.enter()
but its really a stab in the dark ... since you have not provided enough information to actually answer your question. ... (really I guess this question should be closed until OP provides sufficient datas)
you can test this by just running
loser_test = Loser()
and if you see a print that is almost definately your problem
Upvotes: 0
Reputation: 117961
Why don't you just use random.choice
def enter(self):
print random.choice(self.snippets)
Upvotes: 3