You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python对象实例中正确存储值?OOP新手求助

问题分析

你遇到的核心问题是类的属性引用不统一:

  • 初始化时你定义了私有属性self.__count
  • 但在set_count方法里,你给self.count(一个全新的公共属性)赋值,根本没修改到self.__count
  • 而__str__方法一直读取的是self.__count,所以不管你怎么调用set_count,打印实例时始终显示初始的0。

另外还有两个小细节需要修正:

  1. nfile.close少了括号,应该是nfile.close(),否则文件不会正确关闭
  2. 裸except会捕获所有异常,建议更精准地捕获FileNotFoundError,避免隐藏其他问题
修改后的代码
#! /usr/bin/python3
class WordCounter:
    def __init__(self, count = 0):
        self.__count = count  # 私有属性,双下划线开头

    def set_count(self, path):
        try:
            with open(path, "r") as nfile:  # 用with语句自动管理文件,无需手动close
                line = nfile.read()
                file_list = line.split()
                lower_case_list = [word.lower() for word in file_list]
                print(lower_case_list)
                self.__count = len(lower_case_list)  # 这里更新私有属性__count
        except FileNotFoundError:
            print("Could not open file: 文件不存在或路径错误")

    def get_word_count(self):
        return self.__count  # 读取私有属性__count

    def __str__(self):
        return "Total word count is: " + str(self.__count)  # 同样读取__count

if __name__ == "__main__":
    count = WordCounter()
    print(count)
    count.set_count("/home/swim/Desktop/word_counter.txt")
    print(count.get_word_count())
    print(count)
关键修改点说明
  • 统一属性引用:把set_count里的self.count改成self.__count,确保修改的是初始化时定义的私有属性
  • 用with语句管理文件:避免忘记关闭文件的问题,代码更简洁安全
  • 精准捕获异常:只捕获FileNotFoundError,其他异常会正常抛出,方便调试
  • get方法返回正确属性:get_word_count现在返回的是self.__count,和set操作的是同一个变量

这样修改后,运行代码就会得到你想要的结果:

Total word count is: 0
['here', 'is', 'a', 'bunch', 'of', 'text.', 'hopefully', 'all', 'of', 'this', 'gets', 'counted', 'correctly.', 'here', 'it', 'goes.']
16
Total word count is: 16

另外,如果你不想用私有属性(双下划线),也可以把所有__count改成count,这样代码更简洁,但私有属性的好处是可以避免外部直接修改属性值,更符合OOP的封装原则。

内容的提问来源于stack exchange,提问作者user8028854

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:49:25