0

For an assignement for school I need to make a chess game in python. But I'm stuck at a little obstacle.

I want the user to make a chess-piece like this:

p=Pawn(White)

And I want a print to work like this:

print(p) ##Output: White pawn

And in order to get this done I need to use class inheritance, but it doesn't work for me. Here is what I have currently:

WHITE=1
BLACK=2
class ChessPiece:
 def __init__(self,color):
 self.color=color
 def __str__(self):
 if self.color==1:
 print('Witte',self.name)
 else:
 print("Zwart ",self.name)
class Pawn(ChessPiece):
 def __init__(self):
 self.naam='pawn'
 self.kleur=kleur
asked Nov 6, 2016 at 11:49
5
  • Is the name self.naam or self.name. You must choose and use the same everywhere. Commented Nov 6, 2016 at 11:51
  • Shouldn't the variables be called the same? I mean, name and color on both classes, not naam and kleur. Commented Nov 6, 2016 at 11:51
  • As a sidenote, a common trick with inheritance is to use self.__class__.__name__. That gives you the name of the class, here that would be Pawn. Commented Nov 6, 2016 at 11:52
  • 2
    "it doesn't work" isn't a useful problem description; give a minimal reproducible example. Commented Nov 6, 2016 at 11:59
  • Since you have only two colours in chess, a somewhat better choice than 1,2 would be 0,1 or True,False. Commented Nov 6, 2016 at 18:30

1 Answer 1

1

This is modified version of your code:

WHITE=1
BLACK=2
class ChessPiece:
 def __init__(self,color):
 self.color=color
 def __str__(self):
 if self.color==1:
 return "White {}".format(self.__class__.__name__)
 else:
 return "Black {}".format(self.__class__.__name__)
class Pawn(ChessPiece):
 def __init__(self, color):
 ChessPiece.__init__(self,color)
 self.naam = 'pawn'
 self.kleur = 'kleur'
p = Pawn(WHITE)
print(p) 

Some points was neglected in your code that is __str__ should return a string and not to print it and you should call base class __init__ in successor

Bryan Oakley
388k53 gold badges581 silver badges738 bronze badges
answered Nov 6, 2016 at 12:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.