繁体   English   中英

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

[英]Creating a copy of a class with a different constructor

所以我有一个班级女王。 我想将此实例传递给一个函数,然后在该函数中我要创建一个皇后(或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)()

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM