Python 中有三种不同类型的方法:实例方法、类方法和静态方法。它们有不同的使用场景和调用方式。
一、三种方法对比
| | | |
|---|
| 定义装饰器 | | @classmethod | @staticmethod |
| 第一个参数 | self | cls | |
| 访问权限 | | | |
| 调用方式 | 实例.方法() | 类.方法() | 类.方法() |
| 主要用途 | | | |
二、实例方法
1. 基本用法
class Student: def __init__(self, name, score): self.name = name self.score = score # 实例方法 - 操作实例数据 def get_grade(self): if self.score >= 90: return "优秀" elif self.score >= 70: return "良好" elif self.score >= 60: return "及格" else: return "不及格" def update_score(self, new_score): self.score = new_score return f"成绩更新为: {self.score}"# 使用student = Student("张三", 85)print(student.get_grade()) # 输出: 良好print(student.update_score(92)) # 输出: 成绩更新为: 92print(student.get_grade()) # 输出: 优秀
2. 实例方法访问类变量
class BankAccount: # 类变量 interest_rate = 0.03 # 年利率3% bank_name = "中国银行" def __init__(self, owner, balance): # 实例变量 self.owner = owner self.balance = balance # 实例方法可以访问类变量 def calculate_interest(self): return self.balance * self.interest_rate def get_account_info(self): return f"{self.bank_name} - {self.owner}: 余额{self.balance}元"# 使用account = BankAccount("李四", 10000)print(account.calculate_interest()) # 输出: 300.0print(account.get_account_info()) # 输出: 中国银行 - 李四: 余额10000元
三、类方法
1. 基本用法
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day # 类方法 - 操作类级别的数据 @classmethod def from_string(cls, date_string): """从字符串创建Date对象 - 替代构造方法""" year, month, day = map(int, date_string.split('-')) return cls(year, month, day) # 相当于 Date(year, month, day) @classmethod def get_current_date(cls): """获取当前日期""" from datetime import datetime now = datetime.now() return cls(now.year, now.month, now.day) def __str__(self): return f"{self.year}-{self.month:02d}-{self.day:02d}"# 使用类方法创建对象date1 = Date(2023, 12, 1) # 普通构造方法date2 = Date.from_string("2023-12-01") # 类方法构造date3 = Date.get_current_date() # 类方法获取当前日期print(date1) # 输出: 2023-12-01print(date2) # 输出: 2023-12-01print(date3) # 输出: 当前日期
2. 类方法修改类变量
class Configuration: # 类变量 theme = "light" language = "zh-CN" debug_mode = False def __init__(self, user): self.user = user @classmethod def set_theme(cls, new_theme): """修改主题配置""" cls.theme = new_theme return f"主题已切换为: {new_theme}" @classmethod def set_language(cls, new_language): """修改语言配置""" cls.language = new_language return f"语言已切换为: {new_language}" @classmethod def get_config(cls): """获取当前配置""" return { "theme": cls.theme, "language": cls.language, "debug_mode": cls.debug_mode }# 使用类方法修改类变量config1 = Configuration("用户A")config2 = Configuration("用户B")print("修改前:", Configuration.get_config())# 通过类调用类方法Configuration.set_theme("dark")Configuration.set_language("en-US")print("修改后:", config1.get_config()) # 所有实例都受影响print("修改后:", config2.get_config()) # 所有实例都受影响
四、静态方法
1. 基本用法
class MathUtils: # 静态方法 - 工具函数,不依赖类或实例数据 @staticmethod def add(a, b): return a + b @staticmethod def multiply(a, b): return a * b @staticmethod def is_prime(n): """判断是否为质数""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True @staticmethod def factorial(n): """计算阶乘""" if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result# 使用静态方法print(MathUtils.add(5, 3)) # 输出: 8print(MathUtils.multiply(4, 6)) # 输出: 24print(MathUtils.is_prime(17)) # 输出: Trueprint(MathUtils.factorial(5)) # 输出: 120# 也可以通过实例调用(但不推荐)utils = MathUtils()print(utils.add(2, 3)) # 输出: 5
2. 静态方法在类中的使用
class StringProcessor: def __init__(self, text): self.text = text # 实例方法 def process(self): """处理文本""" words = self._split_words(self.text) cleaned_words = [self._clean_word(word) for word in words] return ' '.join(cleaned_words) # 静态方法 - 工具函数 @staticmethod def _split_words(text): """分割单词""" return text.split() @staticmethod def _clean_word(word): """清理单词""" return word.strip().lower() # 静态方法 - 验证函数 @staticmethod def is_valid_text(text): """验证文本是否有效""" return isinstance(text, str) and len(text.strip()) > 0# 使用processor = StringProcessor("Hello WORLD! ")result = processor.process()print(result) # 输出: hello world!# 直接使用静态方法print(StringProcessor.is_valid_text("")) # 输出: Falseprint(StringProcessor.is_valid_text("Hello")) # 输出: True
总结
三种方法的核心区别:
实例方法:操作具体对象的数据,第一个参数是 self
类方法:操作类级别的数据,第一个参数是 cls,用 @classmethod 装饰
静态方法:与类相关的工具函数,无特殊参数,用 @staticmethod 装饰
选择原则:
需要访问实例数据 → 使用实例方法
需要操作类数据或创建替代构造方法 → 使用类方法
需要工具函数但与类相关 → 使用静态方法
不确定时,优先使用实例方法
合理使用这三种方法可以让代码更加清晰和易于维护!