深入浅析python继承问题,浅析python继承
深入浅析python继承问题,浅析python继承
有如下的代码:
class p1: def __init__(self,a,b): print("init in p1") self.a1=a self.b1=b self.f1() def f1(self): print("f1 in p1") class c1(p1): def __init__(self,a,b,c=2): print("init in c1") p1.__init__(self,a,b) self.c1=c self.f1() def f1(self): print("f1 in p2") class c2(c1): pass c=c2(11,22) print(c.a1) print(c.b1) print(c.c1)
然后代码的运行结果如下:
F:\python_code\test>python class_init.py init in c1 init in p1 f1 in p2 f1 in p2 11 22 2
关于的代码的运行过程,我有以下的疑问,我在 c1 的 __init__ 函数中会调用到p1.__init__(),然后会每次都是运行 c1.f1() 函数,没有运行 p1.f1() 的函数,在 p1 运行的 f1(),怎么也是 c1.f1()。为什么?
原因分析:
p1.__init__(self,a,b)
这行代码中的self是c1的对象。所以传给p1里面的self也就是c1的呀。
以上内容所述通过代码给大家介绍了python继承问题,希望对大家有所帮助!
相关内容
- 整理Python 常用string函数(收藏),pythonstring
- Python 常用string函数详解,python函数详解
- python中string模块各属性以及函数的用法介绍,pythonstr
- 浅谈Python的文件类型,
- 深入理解python中的浅拷贝和深拷贝,深入理解python拷贝
- Windows下Python使用Pandas模块操作Excel文件的教程,
- Windows中安装使用Virtualenv来创建独立Python环境,virtual
- python语言使用技巧分享,python使用技巧分享
- Python中Collections模块的Counter容器类使用教程,pythoncol
- Google开源的Python格式化工具YAPF的安装和使用教程,py
评论关闭