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

Python CipherTest类调用方法始终输出Testing问题排查

问题根源

代码始终输出"Testing"由两处核心错误导致,确实存在类方法使用上的认知偏差:

  • 方法逻辑未使用传入的用户参数:shift_to_right、shift_to_left两个方法虽然定义了text、shift形参,但循环遍历文本、计算位移时,全部引用的是实例初始化时写死的self.text(初始值就是"Testing")和self.shift(初始值为0)。位移量为0时,凯撒密码左移右移都不会改变字符,自然永远返回初始的"Testing"字符串,和用户输入没有任何关系。
  • 实例方法调用写法不规范:当前用CipherTest.shift_to_left(Cipher_Message, 参数)的写法语法上可运行,但属于Python早期未绑定方法的调用逻辑,常规写法是直接通过实例调用方法,Python会自动将实例绑定到self参数,不需要手动传入。
修正后可运行代码
class CipherTest:
    def __init__(self):
        self.shift = 0
        self.direction = 'r'
        self.text = "Testing"
    
    # 右移加密
    def shift_to_right(self, text, shift):
        encrypted_text = ""
        # 遍历用户传入的文本,而非实例默认的self.text
        for i in range(len(text)):
            c = text[i]
            if c == ' ':
                encrypted_text += ' '
            # 大写字符加密,使用传入的位移量
            elif c.isupper():
                encrypted_text += chr((ord(c) + shift - 65) % 26 + 65)
            # 小写字符加密
            else:
                encrypted_text += chr((ord(c) + shift - 97) % 26 + 97)
        return encrypted_text
    
    # 左移加密
    def shift_to_left(self, text, shift):
        encrypted_text = ""
        for i in range(len(text)):
            c = text[i]
            if c == ' ':
                encrypted_text += ' '
            elif c.isupper():
                encrypted_text += chr((ord(c) - shift - 65) % 26 + 65)
            else:
                encrypted_text += chr((ord(c) - shift - 97) % 26 + 97)
        return encrypted_text
    
if __name__ == "__main__":
    user_text = str(input())
    user_shift = int(input())
    user_direction = str(input().lower())
    cipher_message = CipherTest()
    if user_direction == 'l':
        # 标准实例方法调用,自动绑定self,无需手动传入实例
        print(cipher_message.shift_to_left(user_text, user_shift))
    if user_direction == 'r':
        print(cipher_message.shift_to_right(user_text, user_shift))
补充说明

如果要更贴合面向对象的封装设计,可以把用户输入的文本、位移量、方向作为参数传入__init__方法,赋值为实例属性,加密方法不需要额外接收参数,直接读取self的对应属性计算即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 03:27:51