Python错误“ 缺少1个必需的位置参数:'self'”

问题描述 投票:0回答:1

Python的新手。尝试创建一个简单的示例,演示2个级别的抽象。收到错误TypeError:'HPNotebook'对象不可调用“

我浏览了无数示例,但仍然感到困惑。

要理解,我已经在代码中显示了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
python abstraction
1个回答
1
投票

只需将self()上的super()替换为HPNotebook.__init__,然后将HP.scroll()上的super().scroll()替换为HPNotebook.scroll

class HPNotebook(HP):
    def __init__(self):
        super()
    def click(self):
        print("HP Click")    
    def scroll(self):
        super().scroll()

也请检查this link以更好地了解python继承。


0
投票
class HPNotebook(HP):
    def __init__(self):
        self()
    def click(self):
        print("HP Click")    
    def scroll(self):
        HP.scroll()

__init__中,您要调用的此self函数是什么?我希望您希望在这里使用super__init__

scroll中,您试图调用class方法scroll。如果没有instance参数,则必须提供实例名称。而是尝试从super实例调用scrollself方法。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.