Python类中调用方法时self.方法名和类名.方法名(self)的区别是什么
两种类内方法调用方式的区别
二者本质逻辑完全不同,并非只是写法风格差异,核心区别在于方法查找逻辑不同:
self.other():遵循Python的方法解析顺序(MRO),会从实例所属的类开始,沿着继承链向上查找other方法,天然支持多态特性Classy.other(self):属于硬编码调用,直接指定执行Classy类中定义的other方法,跳过了正常的方法查找流程
差异示例
示例1:继承重写场景
第一种写法(self.other())会调用子类重写后的方法:
class Classy: def other(self): print("other from Classy") def method(self): print("method") self.other() # 定义子类重写other方法 class SubClassy(Classy): def other(self): print("other from SubClassy") obj = SubClassy() obj.method()
输出:
method other from SubClassy
第二种写法(Classy.other(self))会强制调用父类的原始方法,无视子类重写:
class Classy: def other(self): print("other from Classy") def method(self): print("method") Classy.other(self) class SubClassy(Classy): def other(self): print("other from SubClassy") obj = SubClassy() obj.method()
输出:
method other from Classy
示例2:实例自定义方法场景
如果给单个实例手动绑定自定义的other方法,两种写法的差异也会体现:
class Classy: def other(self): print("other from Classy") def method1(self): self.other() def method2(self): Classy.other(self) obj = Classy() # 给当前实例单独绑定自定义other方法 def custom_other(self): print("other from 实例自定义") obj.other = custom_other.__get__(obj, Classy) obj.method1() obj.method2()
输出:
other from 实例自定义 other from Classy
适用场景
通常开发中优先使用self.xxx()的写法,扩展性更强、符合面向对象的多态设计;只有当你明确需要强制调用当前类的原始方法、不需要考虑子类重写逻辑时,才使用类名硬编码调用的写法。
内容的提问来源于stack exchange,提问作者Leona
相关产品推荐
相关产品推荐

