美文网首页
Python类继承和NotIplementedError

Python类继承和NotIplementedError

作者: hello_world_cxm | 来源:发表于2020-02-20 23:29 被阅读0次

    NotIplementedError异常,让我对python的继承语法有了更加深刻的理解。
    你不妨可以猜猜下面代码,inst.run()方法最后会打印什么东西出来,会不会引发异常呢?

    class ClassDemo:
        def test_demo(self):
            print('我是父亲test_demo')
            raise NotImplementedError("我没有被执行")
        def run(self):
            print('我是父类run方法')
            self.test_demo()
    class ChildClass(ClassDemo):
        # pass
        def test_demo(self):
            print('我是儿子test_demo')
        
    inst = ChildClass()
    print(inst)   #<__main__.ChildClass object at 0x000002ADC1F95488>
    inst.run()
    

    不知道读者们,反正我刚开始以为会引起异常,因为调用的是父类的test_demo方法 (勿喷,我是小白),因为很理所当然的认为,inst调用run方法,但是在子类中没有这个run方法,然后就会往上扬找,找到父类的run方法,接着调用test_demo()方法,因为该语句是在父类作用域中的,不可能调用的是子类的test_demo实例方法。很明显,我错了~
    这个错误让我想起了self是什么,“self就是代表实例本身”。之前不理解这句话,现在明白了。
    不妨可以print(self) 看看self是何方神圣!
    结果返回 <main.ChildClass object at 0x000002ADC1F95488>
    然后inst实例调用run()方法,我猜这个self会传进这个run()方法中,因为子类没有run()方法,所以唯有往上找,找到父类的run方法,然后run(self)这个self代表的就是inst实例本身,所以self.test_demo(),其实就是inst.test_demo()因为,子类有test_demo()方法,所以就打印出了 “print('我是儿子test_demo')”
    所以,我之前错了,是没有认识到self的真实含义。捂脸哭~
    当然,如果子类中有run方法,那么调用的肯定是子类的run方法。因为子类调用方法时,都会先从自己的作用域找有没有这个方法,如果没有再到父类中找。

    相关文章

      网友评论

          本文标题:Python类继承和NotIplementedError

          本文链接:https://www.haomeiwen.com/subject/tjzfqhtx.html