Reputation: 17
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
Upvotes: 0
Views: 189
Reputation: 10971
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
Upvotes: 1