我不明白为什么我收到以下错误,并希望得到一些建议。感谢。
错误:
Traceback (most recent call last):
File "test.py", line 5, in <module>
ciphertext = md.encrypt(plaintext)
File "/Volumes/Mac/Computer/Programming/Cryptography/crypto.py", line 87, in encrypt
ciphertext = Text()
TypeError: __init__() takes exactly 2 arguments (1 given)
代码:
import crypto
plaintext = crypto.Text('plaintext.txt')
md = crypto.MonomeDinome('fred', 'wilma')
ciphertext = md.encrypt(plaintext)
print ciphertext
Crypto.py包含以下代码:
class Text:
def __init__(self, filename):
self.load(filename)
def load(self, filename):
fp = open(filename, "r")
self.rawtext = fp.read()
fp.close
self.text = self.convert(self.rawtext)
def convert(self, txt):
rval = ""
for c in txt.upper():
if c.isalpha():
rval += c
return rval
def set(self, lst):
self.text = "".join(lst)
def get(self):
return self.text
def __str__(self):
rval = ""
pos = 0
for c in self.text:
rval += c
pos += 1
if pos % 60 == 0:
rval += '\n'
elif pos % 5 == 0:
rval += " "
return rval
class MonomeDinome:
def __init__(self, dkw, lkw):
self.digitsKey = self.digitsScramble(dkw)
self.lettersKey = self.lettersScramble(lkw)
def digitsScramble(self, dkw):
dkl = list((dkw.upper() + "ZZZZZZZZZZ")[0:10])
for i in "0123456789":
pos = self.findLowestLetter(dkl)
if pos != -1:
dkl[pos] = i
return "".join(dkl)
def findLowestLetter(self, lst):
pos = -1
lowest = ''
for i in range(len(lst)):
if lst[i].isalpha():
if (lowest == '') or (lst[i] < lowest):
lowest = lst[i]
pos = i
return pos
def lettersScramble(self, lkw):
rlist = []
for a in lkw.upper():
if a == "W":
a = "V"
if a == "J":
a = "I"
if not a in rlist:
rlist.append(a)
for a in "ABCDEFGHIKLMNOPQRSTUVXYZ":
if not a in rlist:
rlist.append(a)
return "".join(rlist)
def __str__(self):
return "digitsKey = " + self.digitsKey + "\n" + \
"lettersKey = " + self.lettersKey
def encrypt(self, plaintext):
rlist = []
for char in plaintext.get():
rlist.append(char)
ciphertext = Text()
ciphertext.set(rlist)
return ciphertext
答案 0 :(得分:4)
构造函数的filename
参数不是可选的,因此在encrypt
中失败:ciphertext = Text()
。它必须是... = Text(some_filename)
答案 1 :(得分:2)
我认为您希望Text
采用0或1选项参数。
class Text:
def __init__(self, filename=None):
if filename is not None:
self.load(filename)
我相信
ciphertext = Text()
是有道理的。
ciphertext.set(rlist)
是设置ciphertext.text
的另一种方式,而不是调用load
方法。
顺便说一下,load
:
def load(self, filename):
...
fp.close() # <--- You need parentheses or else the closed method is not called
您可以使用with
语法来避免错误:
def load(self, filename):
with open(filename, "r") as fp:
self.rawtext = fp.read()
self.text = self.convert(self.rawtext)
使用with
语法,当Python离开fp
套件时,文件句柄with
会自动关闭。