Python 类的继承
2015-07-12 10:27
661 查看
有两个模块 file1.py 和 file2.py
file2中有个基类Base
file1中的Child类继承自 file2.Base
结果:
即使file1中没有函数abc,因为导入的其他模块的类中关联了其他模块中的函数,在file1中是可以执行到的。
但是如果重写了子类的方法,并没有调用父类的,而是重新调用了其他模块的函数,那么便会导致找不到属性,因为file1模块中并没有定义函数abc()
再来看一个例子:
子类中初始化了父类的init,所以执行了父类的init中的
而子类中重写了handler方法,所以执行了子类的handler方法。
因为子类初始化中的
子类中的handler最后执行了setup方法,setup被子类Child重写,如果子类中没有重写,那么便会去找父类中setup方法。
file2中有个基类Base
def abc(self): return "function-abc and name: " + self class Base(object): def __init__(self, name): self.name = name def run(self): return abc(self.name)
file1中的Child类继承自 file2.Base
from file2 import Base class Child(Base): def __init__(self, name=None): if not name: name = 'T1-name' super(Child, self).__init__(name) def run(self): return Base.run(self) print Child().run()
结果:
function-abc and name: T1-name
即使file1中没有函数abc,因为导入的其他模块的类中关联了其他模块中的函数,在file1中是可以执行到的。
但是如果重写了子类的方法,并没有调用父类的,而是重新调用了其他模块的函数,那么便会导致找不到属性,因为file1模块中并没有定义函数abc()
class Child(Base): def run(self): # return Base.run(self) return abc(self.name) # Error
#file2.Base def abc(self): return "function-abc and name: " + self class Base(object): def __init__(self, name): self.name = name def run(self): # 下面两个是Child的类属性和实例属性,但是基类也能执行, # 即使子类没有重写run方法,进行Base.run(self),基类也还是 # 能找到子类的属性。 print self.classattr print self.inattr return abc(self.name) #file1.Child from file2 import Base class Child(Base): classattr = 'Child class attr...' def __init__(self, name=None): self.inattr = "Child instance attr..." if not name: name = 'T1-name' super(Child, self).__init__(name) def run(self): return Base.run(self) print Child().run() # Child class attr... # Child instance attr... # function-abc and name: T1-name
再来看一个例子:
# file1.Base class Base(object): classattr = 'Base class attr' def __init__(self): self.inattr = 'Base instance attr' return self.handler() def handler(self): pass def setup(self): return "Base.setup method" # file2.Child from file1 import Base class Child(Base): classattr = 'Child class attr' def __init__(self): super(Child, self).__init__() self.inattr = "Child instance attr" def handler(self): print self.inattr print 'Child.handler method' print self.setup() def setup(self): return "Child.setup method" print Child() 结果: Child instance attr Child.handler method Child.setup method <__main__.Child object at 0x7fca2e946890>
子类中初始化了父类的init,所以执行了父类的init中的
return self.handler()。
而子类中重写了handler方法,所以执行了子类的handler方法。
因为子类初始化中的
self.inattr = "Child instance attr"写在super之后,所以覆盖了父类的实例属性
self.inattr。
子类中的handler最后执行了setup方法,setup被子类Child重写,如果子类中没有重写,那么便会去找父类中setup方法。
相关文章推荐
- python学习笔记——‘is’和‘==’的区别
- NAO机器人系统下模块生成和python模块调用
- Python爬虫初步
- python while循环控制
- Python绘制CPU曲线图
- Python 有关文件的操作示例
- python urllib库
- 慕课网python基础学习教案(变量和数据类型)
- Python pypinyin、jieba模块
- Python学习资源
- 简单上手Python中装饰器的使用
- 在windows下用opencv for python录像
- stanford parser 使用说明
- 初学python,感受和C的不同
- python3自带web服务器
- python基础课程_2学习笔记3:图形用户界面
- python类的继承的两种方式
- python 命令行参数解析
- Python中的and/or
- python画图