在Python类中,方法调用同类其他方法只需通过self.方法名()
即可实现,这是面向对象编程中封装与代码复用的核心体现。关键亮点包括:通过self
访问实例方法、类方法需用@classmethod
修饰、静态方法独立于实例/类存在。
-
实例方法互调
实例方法默认接收self
参数,调用同类方法时直接使用self.目标方法()
。例如:pythonCopy Code
class Calculator: def add(self, x, y): return x + y def compute(self, a, b): return self.add(a, b) # 调用add方法
-
类方法调用其他方法
类方法使用@classmethod
装饰并接收cls
参数,可调用其他类方法或静态方法:pythonCopy Code
class Logger: @classmethod def log_info(cls, message): cls._format(message) # 调用类方法 @classmethod def _format(cls, msg): return f"[INFO] {msg}"
-
静态方法的限制
静态方法(@staticmethod
)无self
或cls
参数,需通过类名或实例显式调用其他方法:pythonCopy Code
class StringUtils: @staticmethod def reverse(s): return s[::-1] @staticmethod def process(text): return StringUtils.reverse(text) # 需指定类名
-
继承中的方法调用
子类方法可通过super()
调用父类方法,保持继承链:pythonCopy Code
class Parent: def run(self): print("Parent logic") class Child(Parent): def run(self): super().run() # 调用父类方法 print("Child logic")
合理使用方法互调能提升代码可读性,但需注意避免循环调用。静态方法适用于工具类操作,类方法更适合工厂模式等场景。