I was trying to remind myself of OO programming by creating some kind of chess clone in python and found myself with the current issue.
I'd like to give each piece on the board an 'identifier' variable so that it can be displayed on screen e.g : bR would indicate a black rook. However I'm not sre how I can establish this due to colour being a variable being inherited to the rook class, rather than being a part of it.
This is probably a silly question but I've also looked into using the __str__ function for this display but I run into a similar issue that way too. The code I have is below.
I could use another __init__ variable but I'd rather not have to specify every single pawns identifier (P) when the pawn class could surely do the same for me?
class piece(object):
identifier = ' '
def __init__(self, colour):
self.colour = colour
class rook(piece):
identifier = 'R'
rookA = rook('b')
And I'm looking to achieve:
print(rookA.identifier)
"bR"
or
print(rookA)
"bR"
if I'm going about this task in the wrong way, please suggest an alternative!
Thanks
2 Answers 2
There's no issue trying to get the value you need by defining __str__, define it on piece and return self.colour + self.identifier:
def __str__(self):
return self.colour + self.identifier
Now when you print an instance of rook, you'll get the wanted result:
print(rookA)
bR
1 Comment
def __str__(self,colour,identifier) and of course getting an error. My mistake.I'm not sure what issue you had with using __str__, but that is absolutely the right way to go about it.
class Piece(object):
identifier = ' '
def __init__(self, colour):
self.colour = colour
def __str__(self):
return "{}{}".format(self.colour, self.identifier)
return "%s%s" % (colour, identifier)when colour was part of the 'piece' class and not the 'rook' class