我最近开始学习Python,但是我遇到了一个错误的课程和#34; self"没有被定义。我知道有很多关于这个问题的问题,但我无法根据这些答案找出我的代码的问题。
import random
class Encrypt():
def __init__(self, master):
self.master = master
master.title("Encryption using RSA Algorithms")
x = input("Do you want to Encrypt or Decrypt?")
if x=="Encrypt":
print("Redirecting...")
else:
print("Redirecting...")
choice_1 = "Encrypt"
choice_2 = "Decrypt"
if x==choice_1:
y = input("Do you have a public key?")
if y=="Yes":
print("Redirecting...")
else:
print("Generating a key...")
print(self.publickey_generate()) #Error here that self is not defined
else:
z = input("What is your private key?")
def publickey_generate(self):
for output in range (0,1000):
public = random.randint(0, 1000)
if public <= 500:
public += public
else:
public = public - 1
这是我正在制作的代码,它是一个加密和解密软件。错误(由评论标记)是,
line 23, in Encrypt
print(self.publickey_generate(). NameError: name 'self' is not defined
我不知道为什么会这样。任何投入都表示赞赏。
答案 0 :(得分:1)
self指的是对象的实例。
在这里,在第23行,你直接在你的课堂上使用它(在我看来这不是一个很好的方法)。如果您在publickey_generate()
但老实说,这对于对象编程来说似乎是一种奇怪的方式......你应该将所有代码放在类方法中,只将全局变量放在外面(如果需要)。因此,在您的情况下,最简单的方法是将所有代码(publickey_generate()
除外)放在init方法中
答案 1 :(得分:1)
缩进应如下所示:
import random
class Encrypt():
def __init__(self, master):
self.master = master
master.title("Encryption using RSA Algorithms")
x = input("Do you want to Encrypt or Decrypt?")
if x=="Encrypt":
print("Redirecting...")
else:
print("Redirecting...")
choice_1 = "Encrypt"
choice_2 = "Decrypt"
if x==choice_1:
y = input("Do you have a public key?")
if y=="Yes":
print("Redirecting...")
else:
print("Generating a key...")
print(self.publickey_generate()) #Error here that self is not defined
else:
z = input("What is your private key?")
def publickey_generate(self):
for output in range (0,1000):
public = random.randint(0, 1000)
if public <= 500:
public += public
else:
public = public - 1