乐于分享
好东西不私藏

Python 面向对象习题(3/10)

Python 面向对象习题(3/10)

本文首发于微信公众号「拙见python」,基础板块第 6 篇。
适合人群:已阅读第 2 篇:Python 面向对象编程并动手敲过代码的读者。
题目难度:⭐ → ⭐⭐⭐⭐⭐ 逐步提升,建议先自己写,再看答案。


做题须知

  • 每道题标注了考察知识点难度星级
  • 先自己写,写不出来再看答案
  • 答案不是唯一的,能跑通且逻辑正确就行
  • 每道题答案下方附有思路解析

第 3 题:三种方法实战 ⭐⭐

考察知识点:实例方法、@classmethod、@staticmethod

定义一个 StringUtils 类,包含三种方法:

  1. 静态方法is_palindrome(s):判断字符串是否是回文(正读反读一样)
  2. 静态方法count_vowels(s):统计元音字母(aeiou)数量
  3. 类方法from_file(cls, filename):模拟从文件创建实例(返回一个包含文件名的实例)
  4. 实例方法analyze(self):返回该实例对应字符串的分析结果(回文?元音数?)

测试所有方法。

参考答案

class StringUtils:    def __init__(self, text=””):        self.text = text # -------- 静态方法:不依赖实例或类状态 --------    @staticmethod    def is_palindrome(s):        ”””判断是否回文(忽略大小写和空格)”””        cleaned = s.lower().replace(” ”, ””)        return cleaned == cleaned[::-1]    @staticmethod    def count_vowels(s):        ”””统计元音字母数量”””        vowels = set(”aeiouAEIOU”)        return sum(1 for c in s if c in vowels)# -------- 类方法:替代构造器 --------    @classmethod    def from_file(cls, filename):        ”””模拟从文件创建实例”””        print(f”模拟从 {filename} 加载文本...”)        return cls(f”[来自{filename}]”)# 调用 __init__ # -------- 实例方法:操作实例数据 --------    def analyze(self):        return {            ”text”: self.text,            ”length”: len(self.text),            ”is_palindrome”: self.is_palindrome(self.text),            ”vowel_count”: self.count_vowels(self.text),        }# 测试静态方法print(StringUtils.is_palindrome(”racecar”))# Trueprint(StringUtils.is_palindrome(”hello”))# Falseprint(StringUtils.is_palindrome(”A man a plan a canal Panama”))# Trueprint(StringUtils.count_vowels(”Hello World”))# 3# 测试类方法(工厂模式)su = StringUtils.from_file(”data.txt”)print(su.text)# [来自data.txt]# 测试实例方法su2 = StringUtils(”racecar”)print(su2.analyze())# {'text': 'racecar', 'length': 7, 'is_palindrome': True, 'vowel_count': 3}

思路解析

  • 静态方法@staticmethod 不需要 self 或 cls,是逻辑上属于这个类的工具函数。is_palindrome 和 count_vowels不依赖任何实例状态,适合做成静态方法。

  • 类方法@classmethod 接收 cls 参数,常用于工厂方法——from_file 通过 cls(...) 调用构造函数创建实例,比直接 StringUtils(...) 更灵活(子类继承时 cls 会指向子类)。

  • 实例方法 操作 self.text可以调用同类中的静态方法self.is_palindrome(...)。

建议的练习方式

  1. 先自己写——不看答案,能写多少写多少

  2. 卡住了回看文章——第 2 篇对应章节有完整示例

关注「拙见python」,一起写干净的代码。


下一篇预告Python 面向对象习题之4/10