Unindent the ask_number() and ask_yes_no() definitions and remove the self parameter.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
I'm still an ameture at programming, so could you please be a bit more specific about the solution. I don't quite know what you mean by 'Unindent'. Thanks for helping me! :)
I mean remove the definitions from the Player class and write them at the beginning of the line.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
Gribouillis means that obviously those two functions have no business in being in the class Player.
Interestingly I have exactly same functions in module called games for a Blackjack game from one book, without the class Player.
in range(low, high) is not the world's most efficient way to check value is between two limits, here is my code (looks like my coding style, maybe I coded it quickly myself, anyway...)
try:
input = raw_input
except:
pass
def ask_yes_no(prompt='Yes or no (y/n)? '):
while True:
answer = input(prompt).lower()
if answer and answer in 'yn':
return answer
def ask_number(prompt='Number: ', low = None, high = None):
while True:
try:
answer = int(input(prompt))
if low and answer < low:
raise ValueError('Too low')
if high and answer >= high:
raise ValueError('Too high')
return answer
except ValueError as e :
print(e)
print('Try again')
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
You use different style with classes, mostly you like to access methods through an instance of class:
test_module.py
import t_class2
t_class2.hello()
p = t_class2.Player()
p.hello()
test_class2.py
class Player(object):
def hello(self, message='Hello from class Player'):
print(message)
def hello(message='Hello from module %s' % __file__):
print(message)
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Do you think you could maybe explain why the two functions shouldn't be in the Player class?
It's a matter of class design. Normally, functions in a class Player execute player's action or report about player's state, or they may execute code relative to all players (in this case they are class methods or static methods). Technically, one says that each class has a certain number of "responsibilities". General utility functions like ask_yes_or_no() are unrelated to this class.
If you absolutely want to have this functions in the class, write
@staticmethod
def ask_yes_or_no(): # no self parameter
...
and then use game.Player.ask_yes_or_no()
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691