Python:类继承
问题描述:
对于学校的分配,我需要在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
答
这是修改后的版本:
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__
名称是'self.naam'或'self.name'。你必须选择和使用相同的地方。 – spectras
不应该调用变量吗?我的意思是,两个班级的名字和颜色不是'naam'和'kleur'。 –
作为一个旁注,继承的常见技巧是使用'self .__ class __.__ name__'。这给了你班级的名字,在这里就是'Pawn'。 – spectras