【问题标题】:TypeError: __init__() missing 1 required positional argument: 'successorTypeError: __init__() 缺少 1 个必需的位置参数:'successor
【发布时间】:2021-06-05 21:16:21
【问题描述】:

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

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

"现在你需要修改程序,使President对象也有一个属性successor,它保存了行中下一位总统的对象。对于最后一位总统在行中,successor 的值应为 None。该类还应该有一个方法 setSuccessor(next),它将下一任总统分配给 继任者。 示例: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

如您所见,我尝试实现后继者,但我不确定这是否正确。

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

【问题讨论】:

    标签: python class attributes arguments


    【解决方案1】:

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

    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
    

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

    【讨论】:

      猜你喜欢
      • 2019-06-25
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2020-06-13
      相关资源
      最近更新 更多