1

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
  • It was pretty much the same thing, I didn't know how I could use return "%s%s" % (colour, identifier) when colour was part of the 'piece' class and not the 'rook' class Commented Sep 13, 2016 at 15:27
  • But it is inherited; a Rook is-a Piece, and has all of its attributes. Commented Sep 13, 2016 at 15:28

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Okay I was being a little dim, I was trying def __str__(self,colour,identifier) and of course getting an error. My mistake.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.