2016-11-06 226 views
0

对于学校的分配,我需要在Python中制作一个国际象棋游戏。但是我陷入了一个小障碍。Python:类继承

我希望用户做出象棋件这样的:

p=Pawn(White) 

而且我想打印到这样的工作:

print(p) ##Output: White pawn 

而为了完成这件事,我需要使用类继承,但它不适用于我。下面是我目前:你的代码

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 
+0

名称是'self.naam'或'self.name'。你必须选择和使用相同的地方。 – spectras

+0

不应该调用变量吗?我的意思是,两个班级的名字和颜色不是'naam'和'kleur'。 –

+0

作为一个旁注,继承的常见技巧是使用'self .__ class __.__ name__'。这给了你班级的名字,在这里就是'Pawn'。 – spectras

回答

0

这是修改后的版本:

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) 

一些点在你的代码是__str__应该返回一个字符串,而不是将其打印出来,你被忽视应继续调用基类__init__