Search code examples
pythonabstraction

Python Error " <method> missing 1 required positional argument: 'self' "


New to Python. Trying to create a simple example that demonstrates abstraction to 2 levels. Getting an error TypeError: 'HPNotebook' object is not callable "

I've looked through tons of examples and am still stumped.

To understand I have shown the 3 levels in the code.
Can you point me to someplace that helps explain this problem and how to eliminate it or offer a suggestion as to how to correct this. Thanks

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

Solution

  • Just replace self() with super() on HPNotebook.__init__ and replace HP.scroll() with super().scroll() on HPNotebook.scroll.

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

    Also, check this link for better understanding about python inheritance.