首页 > 解决方案 > 如何删除子类中的继承函数?

问题描述

注意:它在python中。简化的代码是,

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

问题是,你如何做到让 notmain.unneededfunction 不存在(即调用它会导致错误)?

标签: pythonsubclass

解决方案


如果你不想notmain拥有unneededfunctionthennotmain不应该是main. 以这种方式对抗系统,它打败了整个继承点。

如果您真的坚持这样做,notmain可以重新定义unneededfunction并引发如果unneededfunction不存在时会引发的相同异常,AttributeError. 但是再一次,你违背了粮食。

除此之外,您不能删除unneededfunctionfrom,notmain因为notmain它不拥有该方法,它的父类拥有main


推荐阅读