Python类继承的super用法
1、打开python开发工具IDLE,新建‘supertest.py’文件,并写代码如下:class A: def test(self): print ('test')class B(A): pass b = B()b.test()
2、F5运行代码,虽然子类没有写任何方法,但是可以成功调用到父类的方法,这就是继承
3、显示调用父类方法,代码如下:class A: def test(self): print ('test')class B(A): def test(self): A.test(self)b = B()b.test()
4、F5运行代码,可以成功调用到父类的方法
5、改写代码,使用super方式调用,好处是可以避免使用父类名class A: def test(self): print ('test')class B(A): def test(self): super(B,self).test() b = B()b.test()
6、F5运行代码,依然可以成功调用到父类的方法
7、上面第五步就是正确的写法不要图简单,写成下面形式class A: def test(self): print ('test'像粜杵泳)class B(A): def test(self): super(self.__class__,self).test() b = B()b.test()在这个例子中,虽然写成self.__class__没有问题,但是在有些多重继承时候,会产生问题,建议养成良好的代码习惯
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:54
阅读量:75
阅读量:31
阅读量:60
阅读量:52