python super()

为什么要用 super()

当子类重写了父类方法时,又想调用父类的同名方法时,就需要用到 super()

关于super函数的详细解释

Python - 面向对象编程 - super() - 小菠萝测试笔记 - 博客园 (cnblogs.com)

 

 

class FooGrandParent(object):
	def __init_(self):
		self.name = "FooGrandParent"
	def print(self):
		print("this is FooGrandParent")

class FooParent(FooGrandParent):
	def __init__(self):
		self.name = "FooParent"
		self.name2 = "FooParentName2"
		super(FooParent,self).__init__()
	def print(self):
		print("this is FooParent")

class FooChild(FooParent):
	def __init__(self):
		super(FooChild, self).__init__()
		self.name = "FooChild"
	def print(self):
		print("this is FooChild")

if __name__ == '__main__':
	foo = FooChild()
	# foo.print()
	# print(foo.name2)
	print(foo.name)

  

posted @ 2021-09-12 17:04  朵朵奇fa  阅读(755)  评论(0编辑  收藏  举报