Reputation: 123
I recently started learning Python and I ran into an error with classes and "self" not being defined. I know that there are a lot of questions about this issue, but I could not figure out the problem with my code based on those answers.
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
This is the code that I am making, it is an encryption and decryption software. The error (marked by a comment) is,
line 23, in Encrypt
print(self.publickey_generate(). NameError: name 'self' is not defined
I don't know why this is happening. Any inputs are appreciated.
Upvotes: 0
Views: 3028
Reputation: 1079
Indents should look like:
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
Upvotes: 2
Reputation: 505
self is refering to the instance of the object when you are in a method of the class.
Here, in line 23, you are using it directly in your class (which is not a good way to do it in my opinion). It should work if you remove the self before publickey_generate()
But honestly it seems a really odd way for object programming... You should put all your code in the class methods and only global variable outside (if needed). So in your case, the easiest would be to put all your code (except publickey_generate()
) in your init method
Upvotes: 1