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

Python Encoder类中函数无法接收参数的问题求助

解决Python类成员函数参数传递错误问题

错误原因分析

你的代码存在三个关键问题,导致参数传递失败:

  • 实例方法的第一个参数命名错误:类中的实例方法必须以self作为第一个参数(代表当前实例),你把file_to_chars的第一个参数写成了Encoder,不符合Python语法规范。
  • 错误调用实例方法:直接通过类名Encoder调用encode方法,未先创建类的实例,导致self参数无法正确绑定。
  • 内部方法调用多余传参:在encode中调用file_to_chars时,错误传递Encoder作为第一个参数,实例方法调用时self会自动传入,无需手动传递。

修正后的完整代码

Encoder类代码

import string
import random

class Encoder():
    def __init__(self):
        self.chars = " " + string.punctuation + string.digits + string.ascii_letters
        self.chars = list(self.chars)
        self.key = self.chars.copy()
        random.shuffle(self.key)
    
    def create_files(self):
        with open("key.txt", 'a') as key_file:
                key_file.write(str(self.key))  

        with open("encrypted.txt", 'a') as encrypted_file:
            encrypted_file.write("new file")
        
    def file_to_chars(self, file_name):  # 第一个参数改为self
        with open(file_name, 'r') as user_file:
                words = user_file.readlines()
                chars_list = []
                for word in words:
                    for char in list(word):
                        chars_list.append(char)
                while "\n" in chars_list:
                    chars_list.remove("\n")
                    
        return chars_list            


    def encode(self, user_input):
        # 去掉多余的Encoder参数,直接传user_input
        original = self.file_to_chars(user_input)
        encryption = ""
        for letter in original:
            index = self.chars.index(letter)
            encryption += self.key[index]
        
        with open("encrypted.txt", 'w') as encrypted_file:
            encrypted_file.write(str(encryption))
        try:
            return open("encrypted.txt", 'r')
        except:
            print("Error, try again. ")

调用代码

from encoder import Encoder

ui = input('name of file: ')
# 先创建Encoder实例,再调用实例的encode方法
encoder = Encoder()
f = encoder.encode(ui)
print(f.read())

关键修改说明

  1. file_to_chars方法参数修正:将第一个参数从Encoder改为self,这是Python类实例方法的标准写法,self会自动指向当前创建的类实例,让方法可以访问类中的成员变量(比如self.chars)。
  2. 实例化类后调用方法:先创建Encoder的实例对象encoder,再通过实例调用encode方法,这样encode方法中的self会正确绑定到这个实例。
  3. 内部方法调用修正:在encode中调用file_to_chars时,只需要传递user_input参数,self会被Python自动传入方法中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:05:30