栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 重写与 super

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 重写与 super

Python 父类方法重写

通常情况下,继承父类后,有时候要扩展父类的类方法的功能来满足子类的需求。

父亲会写字,但不会写代码

class Father:
	# 我会写字
	def write(self):
		print("我会写字")

class Son(Father):
	# 重写Son类的write()方法
	# 我会代码
	def write(self):
		print("我会写代码")
		
son = Son()
son.write()
super()函数
class Father:
	def __init__(self, name):
		self.name = name
	def write(self):
		print("我会写字")

class Son:
	def __init__(self, code):
		self.code = code
	def coding(self):
		print("我会写代码:", self.code)

class Person(Father, Son):
	pass

person = Person('父亲')

# 调用父类中的 write() 方法

person.write()

person.coding()

运行结果:
我会写字
Traceback(most recent call last):
File"",line1,in
AttributeError:'Person’object has no attribute ‘coding’


调用Person.coding时报错,Person继承Father与Son,它们都有__init__(构造方法),所以Son的构造方法被“遮蔽”self.code = code没有运行,调用coding()方法时并没有找到self.code。

调用父类构造方法的方式有2种:

  1. super()函数:该函数只能调用第一个直接父类的构造方法。
  2. 用类调用方法,只不过需要额外备注类名(可以调用所以直接父类的构造方法):

super() 函数有一种更简单的语法格式,推荐大家使用这种格式:
super()__init__(self, ...)


修改上面程序,调用其他构造方法(__init):

class Father:
	def __init__(self, name):
		self.name = name
	def write(self):
		print("我会写字")

class Son:
	def __init__(self, code):
		self.code = code
	def coding(self):
		print("我会写代码:", self.code)

class Person(Father, Son):
	def __init(self, name, code):
		# 调用 People 类的构造方法
		super().__init__(name)
		# super(Person, self).__init__(name)	# 执行效果和上一行相同
		# Father.__init__(self, name)	# 使用未绑定方法调用 Father 类构造方法
		# 调用其他父类的构造方法,需手动给 self 传值
		Son.__init__(self, code)

person = Person('父亲', '写代码')

# 调用父类中的 write() 方法

person.write()

person.coding()

输出结果:
我会写字
我会写代码:写代码


Son.__init__(self, code)调用Son(__init__)构造方法,而非Father(__init__)构造方法。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926182.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号