TypeError:_transform()接受2个位置参数,但给出了3个

时间:2018-12-17 13:35:40

标签: python

我学会了CaesarCipher:

In [90]: !cat caesar_cipher.py                                                                                                                        
class CaesarCipher:
    """Construct Caesar cipher using given integer shift for rotation."""
    def __init__(self, shift):
        encoder = [None] * 26
        decoder = [None] * 26
        for k in range(26):
            encoder[k] = chr((k + shift)%26 + ord('A'))
            decoder[k] = chr((k - shift)%26 + ord('A'))  #find the number of Letters
        self.encoder = "".join(encoder)
        self.decoder = "".join(decoder)

    def encrypt(self, message):
        print(self.encoder)
        return self._transform(message, self.encoder)

    def decrypt(self, message):
        return self._transform(message, self.decoder)

    def _transform(original, code):
        msg = list(original)
        for k in range(len(msg)):
            j = ord(msg[k]) - ord('A')
            msg[k] = code[j]
        return "".join(msg)

if __name__ == "__main__":
    cipher = CaesarCipher(3)
    message = "THE EAGLE IS IN PLAY; MEET AT JOE'S."
    coded = cipher.encrypt(message)
    print("Secret: ", coded)
    answer = cipher.decrypt(coded)
    print("Message: ", answer)

它在_trasform上报告错误

In [91]: !python caesar_cipher.py                                                                                                                     
DEFGHIJKLMNOPQRSTUVWXYZABC
Traceback (most recent call last):
  File "caesar_cipher.py", line 29, in <module>
    coded = cipher.encrypt(message)
  File "caesar_cipher.py", line 14, in encrypt
    return self._transform(message, self.encoder)
TypeError: _transform() takes 2 positional arguments but 3 were given

“ _ transform()接受2个位置参数”,我确实给出了2个参数

为什么要给出报告3?

3 个答案:

答案 0 :(得分:6)

您需要将其定义为

def _transform(self, original, code)

答案 1 :(得分:2)

您必须首先添加self参数,例如

def _transform(self, original, code)...

或者您也可以将其作为静态方法。

@staticmethod
def _transform(original, code)...

答案 2 :(得分:1)

_transform()类中无需使用CaesarCipher方法,因为它是一个无状态(因为它不使用实例变量)和它与Ceasar Cipher 没有特殊关系-它是通用字符替换密码。

因此您可以将其定义为常规函数(在任何类之外),而不是命令

return self._transform(message, self.encoder)
return self._transform(message, self.decoder)

(在您的encrypt() and decrypt()方法中)使用

return transform(message, self.encoder)
return transform(message, self.decoder)