Python继承机制

被继承的类称为基类、父类或超类;继承者称为子类,一个子类可以继承它的父类的任何属性和方法。举个例子:

# 类名大写,方法名小写,约定俗称
class Parent:
	def hello(self):
		print("using parent's class...")
	
class Child(Parent):
	pass

p = Parent()
p.hello()
using parent's class...

c = Child()
c.hello()
using parent's class...
  • 子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法

继承

例子:

import random as r
# 父类
Class Fish:
	def __init__(self):
		self.x = r.randint(0, 10)
		self.y - r.randint(0, 10)
	def move(self):
		self.x -= 1
		print("my seat: ", self.x, self.y)
		
# 子类
Class Shark(Fish):
	def __init__(self):
		self.hungry = True
	def eat(self):
		if self.hungry:
			print("i want eat...")
			self.hungry = False
		else:
			print("I am full, don't eat...")
shark = Shark()
shark.move()
Trackback (most recent call last):
   AttributeError: 'Shark' object has no attribute 'x'
# 原因:在shark类中,重写了__init__()方法,但是新的__init__()方法里没有初始化父类的属性(这里是x,y),因此调用move方法就会出错。结局方法:使用super函数
class Shark(Fish):
	def __init__(self):
		super().__init__()
		...
### Python继承机制详解 #### 什么是继承继承是面向对象编程的核心概念之一,它允许一个类(称为子类或派生类)从另一个类(称为父类或基类)中获取属性和方法。这种机制不仅能够实现代码的重用,还能让程序结构更加清晰、易于维护[^2]。 #### 单继承继承是指子类只从一个父类继承特性。以下是单继承的一个简单例子: ```python class ParentClass: def parent_method(self): return "This is from the parent." class ChildClass(ParentClass): def child_method(self): return "This is from the child." child_instance = ChildClass() print(child_instance.parent_method()) # 输出: This is from the parent. print(child_instance.child_method()) # 输出: This is from the child. ``` 在这个例子中,`ChildClass` 继承了 `ParentClass` 的所有方法,并且还可以定义自己的新方法[^4]。 #### 方法重写 如果子类需要改变某些行为,它可以覆盖父类的方法。这被称为方法重写。 ```python class ParentClass: def greet(self): return "Hello from parent!" class ChildClass(ParentClass): def greet(self): return super().greet() + " And hello from child too!" child_instance = ChildClass() print(child_instance.greet()) # 输出: Hello from parent! And hello from child too! ``` 这里使用了 `super()` 函数来调用父类的方法[^3]。 #### 多继承 Python 支持多继承,即一个类可以从多个父类继承。当发生这种情况时,Python会按照一定的顺序查找方法,这个顺序叫做 **Method Resolution Order (MRO)**[^5]。 下面是一个简单的多继承示例: ```python class A: def method(self): return "A's method" class B(A): pass class C(A): def method(self): return "C's method" class D(B, C): pass d_instance = D() print(d_instance.method()) # 输出取决于 MRO ``` 在这种情况下,D 类既继承自 B 又继承自 C。由于 B 和 C 都是从 A 派生出来的,因此实际执行哪个版本的 `method` 将由 MRO 决定。 #### 特殊方法的应用 除了普通的实例方法外,在设计类的时候也可以利用一些特殊的魔法方法来自定义其行为。例如,`__init__`, `__str__`, 或者运算符重载相关的函数等都可以被重新定义以满足具体的需求。 --- ### 总结 通过上述介绍可以看出,Python 中的继承提供了强大的工具用于构建复杂的软件架构。无论是单一还是多重继承模式下都能很好地促进代码复用并减少冗余;而借助于超类访问以及定制化魔术方法等功能,则进一步增强了灵活性与表现力[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值