python2.#与python3.# super()调用父类方法异同

本文介绍了使用Python2.7及3.5版本实现的一个简单的动物追逃游戏,通过蚂蚁与虫子的角色进行点位跳动,模拟追捕过程。文章提供了完整的源代码示例,并展示了如何在不同Python版本中继承父类和调用父类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding:utf-8
'''
Created on 2016年3月30日

Python2.7版本继承父类,调用父类方法的方式源码:

@author: Administrator
'''
import random

class Sprite:
step = [-2,+2,-3,+3]

def __init__(self,gm,point=None):
self.gm = gm
if point is None:
self.point = random.randint(0,20)
else:
self.point = point

def jump(self):
astep = random.choice(Sprite.step)
if 0 <= self.point + astep <= 20:
self.point += astep

class Ant(Sprite,object):
def __init__(self,gm,point=None):
super(Ant,self).__init__(gm,point)
self.gm.set_point('ant',self.point)
def jump(self):
super(Ant,self).jump()
self.gm.set_point('ant',self.point)

class Worm(Sprite,object):
def __init__(self,gm,point=None):
super(Worm,self).__init__(gm,point)
self.gm.set_point('worm',self.point)
def jump(self):
super(Worm,self).jump()
self.gm.set_point('worm',self.point)

class GameMap:
def __init__(self):
self.ant_point = None
self.worm_point = None

def catched(self):
print('ant:',self.ant_point,'worm:',self.worm_point)
if self.ant_point is not None and self.worm_point is not None and self.ant_point==self.worm_point:
return True
def set_point(self,src,point):
if src == 'ant':
self.ant_point = point
if src == 'worm':
self.worm_point = point


if __name__ == '__main__':
gm = GameMap()
worm = Worm(gm)
ant = Ant(gm)
while not gm.catched():
worm.jump()
ant.jump()

 

#coding:utf-8
'''
Created on 2016年3月30日

 

Python3.5.1版本继承父类,调用父类方法的方式源码:

@author: Administrator
'''
import random

class Sprite:
step = [-2,+2,-3,+3]

def __init__(self,gm,point=None):
self.gm = gm
if point is None:
self.point = random.randint(0,20)
else:
self.point = point

def jump(self):
astep = random.choice(Sprite.step)
if 0 <= self.point + astep <= 20:
self.point += astep

class Ant(Sprite):
def __init__(self,gm,point=None):
super().__init__(gm,point)
self.gm.set_point('ant',self.point)
def jump(self):
super().jump()
self.gm.set_point('ant',self.point)

class Worm(Sprite):
def __init__(self,gm,point=None):
super().__init__(gm,point)
self.gm.set_point('worm',self.point)
def jump(self):
super().jump()
self.gm.set_point('worm',self.point)

class GameMap:
def __init__(self):
self.ant_point = None
self.worm_point = None

def catched(self):
print('ant:',self.ant_point,'worm:',self.worm_point)
if self.ant_point is not None and self.worm_point is not None and self.ant_point==self.worm_point:
return True
def set_point(self,src,point):
if src == 'ant':
self.ant_point = point
if src == 'worm':
self.worm_point = point


if __name__ == '__main__':
gm = GameMap()
worm = Worm(gm)
ant = Ant(gm)
while not gm.catched():
worm.jump()
ant.jump()






















转载于:https://www.cnblogs.com/jerryqiqi/p/5337816.html

<think>好的,用户现在问的是关于Pythonsuper().__init__(x)super(Child, self)这两种写法的区别。我之前已经回答过关于多重继承中方法调用顺序的问题,现在用户可能想更深入了解super()的不同用法,或者在实际编码中遇到了相关的问题。 首先,我需要回顾一下super()的基本用法。在Python中,super()用于调用父类方法,尤其是在子类中重写方法时,保持继承链的完整性。用户提到的两种写法,其实是super()在不同Python版本中的使用方式。 接下来,我得确认这两种写法在功能上的区别super().__init__(x)是Python3中的语法,而super(Child, self)则是Python2的写法,不过在Python3中也可以使用。不过,后者需要显式传递子类实例,而前者会自动填充这些参数。 然后,我需要考虑用户为什么会问这个问题。可能他们在阅读旧代码时看到了super(Child, self)的写法,或者在学习过程中遇到了两种写法,不清楚它们的区别适用场景。用户可能在使用Python3,但需要维护或理解旧代码,因此需要了解这两种方式的异同。 另外,用户可能对super()的工作原理不太清楚,尤其是方法解析顺序(MRO)。需要解释super()的动态特性,即它根据MRO来决定调用哪个父类方法,而显式传递类名实例可能会影响这一行为。 还要注意,是否有其他相关的问题需要提及,比如在多重继承中使用super()时的注意事项,或者为什么推荐使用无参数的super()形式。例如,在Python3中,super()不带参数的形式更简洁,减少了代码冗余,也减少了出错的几率,因为自动获取当前类实例的信息。 可能用户还会混淆super(Child, self)显式调用父类初始化方法,比如Parent.__init__(self),这之间的区别。虽然在某些情况下显式调用可行,但在多重继承中可能导致父类方法被多次调用或遗漏,而super()基于MRO的设计可以避免这些问题。 最后,需要总结两者的主要区别,强调Python3中的改进推荐做法,同时说明旧写法的存在原因适用场景,帮助用户在实际开发中正确选择使用。</think>在 Python 中,`super().__init__(x)` `super(Child, self)` 是两种调用父类方法的语法形式,它们的核心区别在于 **参数传递方式** **Python 版本兼容性**。以下是详细对比: --- ### **一、语法差异** #### 1. **`super().__init__(x)`** - **Python 3 特有语法** 自动推断当前类实例,无需显式传递参数。 - **示例**: ```python class Child(Parent): def __init__(self, x): super().__init__(x) # 自动获取 Child 类 self 实例 ``` #### 2. **`super(Child, self)`** - **Python 2/3 兼容语法** 需显式指定子类名 `Child` 实例 `self`。 - **示例**: ```python class Child(Parent): def __init__(self, x): super(Child, self).__init__(x) # 显式传递类名实例 ``` --- ### **二、底层原理** 1. **`super()` 的参数意义** - `super(Child, self)` 表示: - 在 `Child` 类的 MRO 链中,找到当前方法的下一个类。 - `self` 是实例,用于绑定方法调用。 - 无参数的 `super()` 等价于 `super(__class__, self)`(仅在类方法中生效)。 2. **动态性灵活性** - `super(Child, self)` 的类名是硬编码的,若子类改名或继承关系变化,需手动修改。 - `super()` 无需硬编码类名,更灵活且维护性更高。 --- ### **三、场景对比** #### 场景 1:**单继承**(效果相同) ```python class Parent: def __init__(self, x): self.x = x # Python 3 写法 class ChildA(Parent): def __init__(self, x): super().__init__(x) # Python 2/3 兼容写法 class ChildB(Parent): def __init__(self, x): super(ChildB, self).__init__(x) ``` 两者均正确调用 `Parent.__init__`,但 `super()` 更简洁。 --- #### 场景 2:**多重继承**(必须用 `super()` 的链式调用) ```python class A: def __init__(self): print("A") super().__init__() class B: def __init__(self): print("B") super().__init__() class C(A, B): def __init__(self): print("C") super().__init__() c = C() # 输出顺序: C → A → B ``` - **关键点**: - 使用 `super().__init__()` 可自动按 MRO 链调用后续父类方法。 - 若用 `super(A, self).__init__()` 硬编码类名,会破坏 MRO 顺序。 --- ### **四、关键区别总结** | **特性** | `super().__init__(x)` | `super(Child, self).__init__(x)` | |-------------------------|-------------------------------------------|-------------------------------------------| | **Python 版本** | Python 3 专属 | Python 2/3 兼容 | | **参数传递** | 自动推断当前类实例 | 需显式传递类名实例 | | **代码维护性** | 类名修改时无需调整代码 | 类名修改需同步更新硬编码部分 | | **多重继承协作性** | 支持链式调用(依赖 MRO) | 需手动确保调用顺序 | | **代码简洁性** | 更简洁 | 冗余性较高 | --- ### **五、设计建议** 1. **优先使用 `super()`** 在 Python 3 中推荐无参数写法,避免硬编码类名,提高代码可维护性。 2. **仅在需要兼容 Python 2 时使用显式参数** 如维护旧项目或跨版本库。 3. **避免混合使用 `super()` 直接调用父类方法** 例如 `Parent.__init__(self)` 会绕过 MRO,可能导致多重继承逻辑混乱。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值