Python:类inheritan

2024-04-26 04:06:02 发布

您现在位置: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

Tags: 用户nameselfinitdef学校classcolor
1条回答
网友
1楼 · 发布于 2024-04-26 04:06:02

这是您的代码的修改版本:

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__

相关问题 更多 >