Home > Net >  Python Object inheritance
Python Object inheritance

Time:12-25

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 ?

CodePudding user response:

Yes, methods are also inherited from classes. However, you will need to add a parameter to the install method so it can take the app name:

class Phone:
   def install(self, app_name):  # Allow the method to take an input app name
        ...

class InstagramApp(Phone):
    ...

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

app = InstagramApp()
install_app(app, 'instagram')  # Yes, this will also work with the InstagramApp class

CodePudding user response:

Yes - so long as the InstagramApp doesn't delete any of the methods that 'install_app', and the methods return the same types as the Phone class does then it will work.

I am curious as to why to pass the instance and pass the name as text - you could accomplish the sanme by simply ascessing the __name__ variable of the class - so for instance :

`app.__class_.__name__ will equal 'Instagram'

As others have pointed out you need to fix the various function calls.

CodePudding user response:

install_app gets a Phone object. will it work with InstagramApp object? the inheritance class will have the function

class Phone:
   def install(app_name:str):# change type to str
       pass
    

class InstagramApp(Phone):
    pass

def install_app(phone: Phone, app_name):# change the type to Phone Class
   phone.install(app_name)

app = InstagramApp()
install_app(app, 'instagram') #


CodePudding user response:

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")
  • Related