【问题标题】:TypeError: __init__() takes 3 positional arguments but 4 were given errorTypeError: __init__() 接受 3 个位置参数,但给了 4 个错误
【发布时间】:2020-11-02 10:11:49
【问题描述】:
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
    def __init__(self,title,author):
        self.title=title
        self.author=author   
    @abstractmethod
    def display(): pass
class MyBook(Book):
    def __innit__(self,title,author,price):
        self.title = title
        self.author = author
        self.price = price    
    def display(self):
        print("Title: {0}".format(self.title))
        print("Author: {0}".format(self.author))
        print("Price: {0}".format(self.price))
title=input()
author=input()
price=int(input())
new_novel = MyBook(title,author,price)
new_novel.display()

遇到错误:TypeError: init() 采用 3 个位置参数,但给出了 4 个 请给我有关如何解决此错误的想法

【问题讨论】:

    标签: python-3.x typeerror abstract-class


    【解决方案1】:

    您的第二个启动器函数中有错字。在 MyBook 类中将“init”替换为“init”。

    【讨论】:

      【解决方案2】:

      一旦错字__innit__ 更正为__init__TypeError 就会消失

      更正一点:我们应该调用父类的init方法,而不是再次在MyBook类中声明titleauthor成员。这也将带来 oops 继承优势。

      Book.__init__(self, title, author)
      
      from abc import ABCMeta, abstractmethod
      class Book(object, metaclass=ABCMeta):
          def __init__(self, title, author):
              self.title = title
              self.author = author   
          @abstractmethod
          def display(): pass
      class MyBook(Book):
          def __init__(self, title, author, price):
              Book.__init__(self, title, author)
              self.price = price
          def display(self):
              print("Title: {0}".format(self.title))
              print("Author: {0}".format(self.author))
              print("Price: {0}".format(self.price))
      title=input()
      author=input()
      price=int(input())
      new_novel = MyBook(title,author,price)
      new_novel.display()
      

      【讨论】:

        猜你喜欢
        • 2018-03-07
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 2015-07-13
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多