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
1 Answer 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
lang-py
self.naam
orself.name
. You must choose and use the same everywhere.name
andcolor
on both classes, notnaam
andkleur
.self.__class__.__name__
. That gives you the name of the class, here that would bePawn
.1,2
would be0,1
orTrue,False
.