2017-03-09 102 views
0

我最近開始學習Python,並遇到錯誤,類和「自我」沒有被定義。我知道這個問題有很多問題,但是根據這些答案我無法弄清楚我的代碼存在問題。Python錯誤 - 未定義「自我」

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

變化'級加密()'來'級加密(對象):'? – mguijarr

+7

您的縮進需要更正 – Wondercricket

+0

看起來代碼在「__init__」方法下沒有正確縮進 – jakevdp

回答

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 
1

當您在類的方法中時,self指的是對象的實例。

在這裏,第23行中,你直接在你的課堂上使用它(這在我看來並不是一個好的方法)。它應該工作,如果你之前刪除自己publickey_generate()

但老實說,它似乎是一個非常奇怪的方式對象編程...你應該把所有的代碼放在類方法和外部全局變量(如果需要)。所以你的情況,最簡單的是把所有的代碼(除publickey_generate())在你的init方法