猿问

Python 错误“<method> 缺少 1 个必需的位置参数:‘self’”

Python 新手。尝试创建一个简单的示例来演示 2 个级别的抽象。收到错误 TypeError: 'HPNotebook' object is not callable "


我已经浏览了大量的例子,但仍然很难过。


为了理解我已经在代码中显示了 3 个级别。

您能否指出一些有助于解释此问题以及如何消除它或提供有关如何纠正此问题的建议的地方。谢谢


from abc import abstractmethod,ABC   #this is to allow abstraction. the ABC forces inherited classes to implement the abstracted methods.


class TouchScreenLaptop(ABC):

    def __init__(self):

        pass

    @abstractmethod      #indicates the following method is an abstract method.

    def scroll(self):    # a function within the parent

        pass             #specifically indicates this is not being defined

    @abstractmethod      #indicates the following method is an abstract method.

    def click(self):    

        pass             #specifically indicates this is not being defined


class HP(TouchScreenLaptop):

    def __init__(self):

        pass

    @abstractmethod         #indicates the following method is an abstract method.

    def click(self):    

        pass  

    def scroll(self):

        print("HP Scroll")


class HPNotebook(HP):

    def __init__(self):

        self()

    def click(self):

        print("HP Click")    

    def scroll(self):

        HP.scroll()


hp1=HPNotebook()

hp1.click()                  #the 2 level deep inherited function called by this instance

hp1.scroll()                 #the 1 level deep inherited function called by this instance



阿波罗的战车
浏览 114回答 1
1回答

紫衣仙女

只需替换self()为super()onHPNotebook.__init__并替换HP.scroll()为super().scroll()on HPNotebook.scroll。class HPNotebook(HP):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; super()&nbsp; &nbsp; def click(self):&nbsp; &nbsp; &nbsp; &nbsp; print("HP Click")&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; def scroll(self):&nbsp; &nbsp; &nbsp; &nbsp; super().scroll()此外,请查看此链接以更好地了解 python 继承。
随时随地看视频慕课网APP

相关分类

Python
我要回答