我遇到了这段代码的问题。目标是"加密"用户通过反转输入输入的消息。本课程最初是作为代码的功能块编写的,但我想将其转换为面向对象的编程,现在我收到了一个错误。如果我在此代码中有任何其他问题,请通知我。
这是代码
class Encrypt:
def __init__(self,message,translated):
self.message = message # user input
self.translated = translated # encrypted result
def encryptionProcess(self,message): # encrypting functino
i = len(message) - 1
while i >= 0:
self.translated = self.translated + self.message[i]
i = i - 1
m1 = Encrypt(input(),'') # setting the class attributes
m1.encryptionProcess(message) # calling the function
print(Encrypt.translated) # printing the result
这是错误
Traceback (most recent call last):
File "oopEncrypt.py", line 13, in <module>
m1.encryptionProcess(message)
NameError: name 'message' is not defined
答案 0 :(得分:0)
使用self
参数访问类实例属性,作为第一个参数传递给类实例方法。
试试这个:
class Encrypt:
def __init__(self, message):
self.message = message # user input
def encryptionProcess(self): # encrypting functin
translated = "".join(reversed(self.message))
return translated
m1 = Encrypt(input("Enter word to encrypt > "))
translated = m1.encryptionProcess()
print("Encrypted Word:", translated)
self
是当前类的实例。
您可能会发现python 3类文档是一个有用的参考:https://docs.python.org/3.6/tutorial/classes.html