【问题标题】:Python using super to override attributes, unexpected argument error when passing argumentsPython使用super覆盖属性,传递参数时出现意外参数错误
【发布时间】:2018-11-06 12:01:38
【问题描述】:

我有一个国际象棋程序的棋子类,我希望其他棋子继承自:

class Piece:
    def __init__(self, player, diag, straight, opponent, marker, unicode):

        self.player = player
        self.diag = diag
        self.straight = straight
        self.opponent = opponent
        self.marker = marker
        self.unicode = unicode

例如,必须设置特定于自身但属于基类属性的属性的国王类:

from Piece import Piece

class King(Piece):

    def __init__(self, player, opposition, unicode):
        super.__init__(player,False, False, opposition,"K", unicode)
        self.has_moved = False
        self.casle_king = True
        self.castle_queen = True

我的问题是,当我将它们传递给超级函数时,即使我已经在片段中定义了它们,它们也会引发意外的参数错误。

King 从 Piece 继承但又设置不同共享的特定属性的正确方法是什么?

【问题讨论】:

  • super 应该是super()
  • 但是我该如何将 Piece.straight 等特定的布尔值更改为 False?
  • 只需将super 更改为super() 即可。
  • 哦,我明白了,我以为你的意思是把它留给 super 而不传递参数。
  • NB:当然假设是 Python3。在 Python2 中,您需要 super(King, self).__init__(player,False, False, opposition,"K", unicode)

标签: python oop inheritance


【解决方案1】:

你忘记了 super 的括号:

super().__init__(player,False, False, opposition,"K", unicode)

或者:

Piece.__init__(self, player,False, False, opposition,"K", unicode)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2016-09-16
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多