类型错误:__init__() 缺少 1 个必需的位置参数:'successor

时间:2021-03-07 22:40:43

标签: python class attributes arguments

我有一个学校项目。任务是按类别和对象打印三位总统。我已经做了一个具有三个属性的班长:姓名、国家和就职典礼。我所做的。

但接下来的任务是打印每位总统的继任者:

“现在你需要修改程序,让 President 对象也有一个属性 successor 持有该行中下一任总统的对象。对于最后一位总统在行中,successor 的值应该是 None。这个类还应该有一个方法 setSuccessor(next) 将下一任总统分配给 < em>继任者。 示例:clinton.Successor(bush)

现在总统由变量 presidents 表示,该行包含第一任总统。其余的总统由继任者代表。”

所以这是我到目前为止写的,但我不明白:( 我收到了我在主题中写的这个错误。缺少参数后继。但我的猜测是,这不仅是问题所在。

# a) 
class President:

    def __init__(self, president, country, elected, successor):

        self.president = president
        self.country = country
        self.elected = elected
        self.successor = successor

    def write(self):
        print(self.president,"of the", self.country, "inauguration:", self.elected, self.successor)

    def __str__(self):
        return f"{self.president} of the {self.country}, inauguration: {self.elected} {self.successor}"

        
clinton = President("Bill Clinton", "US", "1993")
bush = President("George W Bush", "US", "2001")
obama = President("Barack Obama", "US", "2009")

print(clinton)
print(bush)
print(obama)


presidents =  [President("Bill Clinton", "US", "1993"),
               President("George W Bush", "US", "2001"),
               President("Barack Obama", "US", "2009")]

# b)

def setSuccessor(next):

    successor=next
    clinton.successor(bush)
    bush.sucessor(obama)
    obama.successor = None

如您所见,我已尝试实施后继方案,但我不确定这是否正确。

感谢所有帮助,在此先感谢您!

1 个答案:

答案 0 :(得分:0)

您看到的错误是因为 __init__() 类的 President 方法需要后继参数,但您在创建总裁时没有提供它。

setSuccessor(next) 需要是 President 类的方法。您的代码将其声明为普通函数。另外,不要使用 next 作为变量名,因为它会覆盖内置的 next() 函数:

此外,__init__() 不再需要 successor 参数,或者您最好将其设为默认值 None

class President:

    def __init__(self, president, country, elected, successor=None):
        self.president = president
        self.country = country
        self.elected = elected
        self.successor = successor

    def set_successor(self, successor):
        self.successor = successor


biden = President("Joe Biden", "US", "2021")    # no successor argument supplied - this president has no successor yet
trump = President("Donald Trump", "US", "2017", biden)

harris = President("Kamala Harris", "US", "2021")
biden.set_successor(harris)    # a bold prediction

例如,如果特朗普再次成为总统,您可能想添加一种方法来更新就职年。