Search code examples
pythonobjectinheritance

Python Object inheritance


class Phone:
   def install():
        ...

class InstagramApp(Phone):
    ...

def install_app(phone: "Phone", app_name):
   phone.install(app_name)

app = InstagramApp()
install_app(app, 'instagram') # <--- is that OK ?

install_app gets a Phone object. will it work with with InstagramApp object ?


Solution

  • The inheritance works correctly. install method is inherited from Phone class. But your code doesn't work. When you run it, it will say:

    TypeError: Phone.install() takes 0 positional arguments but 2 were given
    

    What are these two arguments that have been passed?

    Second one is obviously the 'instagram' string. You passed that but no parameter expects it.

    The first one is, Because you invoke that install() method from an instance, Python turns it into a "Method" and automatically fills the first parameter of it to a reference to the instance(this is how descriptors work). But again you don't have any parameter to receive it.

    To make that work:

    class Phone:
        def install(self, name):
            print(self)
            print(name)
    
    
    class InstagramApp(Phone):
        ...
    
    
    def install_app(phone: "Phone", app_name):
        phone.install(app_name)
    
    
    app = InstagramApp()
    install_app(app, "instagram")