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

Python OOP类内函数调用出现NameError问题求助

解决类内部方法调用的NameError问题

你的错误根源是在类的实例方法内部调用其他实例方法时,没有通过self来引用。直接写get_frequancy(self)会被Python当成调用全局函数,而不是类的实例方法,所以触发NameError。

修正步骤:

  1. 修正方法调用方式:在create方法里,调用类内其他方法必须使用self.方法名()的形式:
def create(self):
    self.get_frequancy()  # 用self.引用实例方法
    self.create_pic()
    print("created")
  1. 修复文件路径的属性错误:get_frequancy方法里用了self.file_location,但你的构造方法里定义的是self.filename,需要改成self.filename,否则会触发AttributeError:
def get_frequancy(self):
    with open(self.filename, "r") as f:  # 替换self.file_location为self.filename
        lines = f.read().lower()
    # 后续代码不变
  1. 补充必要的导入:create_pic方法里用到了wordcloud模块,需要在代码开头添加导入语句:
import wordcloud

完整修正后的代码:

import wordcloud

class WordPic:
    
    def __init__(self,filename,outputname):
        self.skipped = ["was","in","the","have","think","these","we","as"]
        self.filename = filename
        self.outputname = outputname
        self.txt_freq = {}
    
    def get_frequancy(self):
        # 修正文件属性名
        with open(self.filename,"r") as f:
            lines = f.read().lower()
        splited_lines = lines.split()
        for line in splited_lines:
            if line not in self.skipped and line.isalpha():
                line = line[0].upper() + line[1:]
                if line not in self.txt_freq:
                    self.txt_freq[line] = 1
                else:
                    self.txt_freq[line] += 1
        return self.txt_freq

    def create_pic(self):
        cloud = wordcloud.WordCloud(background_color="white")
        cloud.generate_from_frequencies(self.txt_freq)
        cloud.to_file("{}.jpg".format(self.outputname))
    
    def create(self):
        # 用self.调用实例方法
        self.get_frequancy()
        self.create_pic()
        print("created")


wc = WordPic("try.txt","done")
wc.create()

额外建议:

  • 方法名拼写修正:get_frequancy应该改为get_frequency(符合英文拼写规范,避免后续混淆)。
  • 可以给文件操作添加异常处理,比如捕获文件不存在的错误,增强代码健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:30:49