使用其他构造函数创建类的副本

时间:2019-01-09 08:53:04

标签: python

所以我有一个班级女王。我想将此实例传递给一个函数,然后在该函数中我要创建一个皇后(或Rook或King)的新实例(基于传入的类可能是Rook,King等),但具有不同的初始输入参数。我希望那很简单

我可以从实用程序类中执行此操作,但我希望在Board类中使用该功能。

# This part works if I do it in the utility class

board.removePiece(pos6)
board.removePiece(pos2)
board.placePiece(pos6, Queen("Black", pos6))

# This part doesnt work

def capturePiece(self, pieceA, pieceB):
    temp = pieceA
    pos = pieceB.position

    self.removePiece(pieceB.position)
    self.removePiece(pieceA.position)

    self.placePiece(pos, temp.create_another(temp.team, pos))

# From the Queen, King, etc, class

def create_another(self, team, position): # Returning constructor
    return type(self, team, position)()

1 个答案:

答案 0 :(得分:1)

对于基类的类方法来说,这可能是一个很好的例子:

class Piece:
    @classmethod
    def create_another(cls, team, position):
        return cls(team, position)
    def __init__(self, team, position):
        self.team = team
        self.position = position
    def __str__(self):
        return str("{} team {} at {}".format(self.__class__,
                             self.team, self.position))

class Queen(Piece):
    pass

class Rook(Piece):
    pass

class Board:
    def placePiece(self, pos, piece):
        print("Place {} at {}".format(piece, pos))
    def removePiece(self, position):
        print("Remove piece at " + str(position))
    def capturePiece(self, pieceA, pieceB):
        temp = pieceA
        pos = pieceB.position

        self.removePiece(pieceB.position)
        self.removePiece(pieceA.position)

        self.placePiece(pos, temp.create_another(temp.team, pos))
    def test(self):
        r = Rook("White", "d4")
        q = Queen("Black", "d6")
        self.capturePiece(q, r)

您可以尝试:

b = Board()
b.test()

如预期那样显示:

Remove piece at d4
Remove piece at d6
Place <class '__main__.Queen'> team Black at d4 at d4

但这通常是一个较差的设计。重复销毁和创建新对象比简单地更改其属性要昂贵得多。而且,无论如何,在 real 棋盘上,您不会创建新的棋子,而不会移动它们,因此您没有真正的理由不只是实施move方法来更改在Piece棋子类上的位置。 / p>