How do you delete an inherited function in a subclass?

Question:

My code basically looks like this

class main:
    def __init__(self):
        pass
    def unneededfunction(self):
        print("unneeded thing")

class notmain(main):
    def __init__(self):
        pass 
    #code for getting rid of unneededfunction here

How do you get rid of notmain.unneededfunction? (i.e., calling it results in an error)

Asked By: noob10293

||

Answers:

If you don’t want notmain to have unneededfunction then notmain should not be a subclass of main. It defeats the whole point of inheritance to fight the system this way.

If you really insist on doing it, notmain could redefine unneededfunction and raise the same exception that would be raised if unneededfunction didn’t exist, AttributeError. But again, you’re going against the grain.

Aside from that, you can’t delete unneededfunction from notmain because notmain doesn’t own that method, its parent class main does.

Answered By: sj95126

Do you need to delete it? (ie, it throws an attribute error). Or can you get away with partial inheritance?

The first answer here should address the latter:
How to perform partial inheritance

If you just want it to throw an error on call this should work:

class notmain(main):
    def __init__(self):
        pass 
    def unneededfunction(self):
        raise NotImplementedError("explanation")

Or you can try the Mixin methods discussed here in structuring the classes:
Is it possible to do partial inheritance with Python?

Answered By: josephvictory
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.