2016-07-10 73 views
-1

下面我試圖做一個簡單的Keygen作爲第一個項目。某處我遇到了自我尚未定義的錯誤。Python - 類 - 自我未定義

我猜它可能是一些容易

import random 

class KeyGenerator(): 
def __init__(self): 

    length = 0 
    counter = 0 
    key = [] 
    Letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] 



def KeyGen4(self): 
    while self.counter != self.length: 
     a = random.choice(self.Letters) 
     print a #test 
     r = (random.randint(0,1)) 
     print r #test 
     if r == True: 
      a = a.upper() 
     else: 
      pass 
     self.key.append(a) 
     self.counter += 1 

    s = ''  
    self.key = s.join(key) 
    print self.key 
    return self.key 

def start(self): 
    selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >') 

    if selection == 'K' or 'k': 
     length = 4 
     keyGen4(self) 

    elif selection == 'N' or 'n': 
     KeyGenN(self) 

    elif selection == 'C' or 'c': 
     length = int(raw_input("Key Length: ")) 
    #KeyGen4(self) # Change later after creating method with more options 

start(self) 
+1

'self.start()'而不是'start(self)'。你爲其他方法做了同樣的錯誤。 –

回答

4
  1. 你的縮進是錯誤的,但我相信這只是一個複製粘貼問題。

  2. start(self)在底部沒有意義,
    確實self是沒有定義。您應該創建一個類的實例,然後調用其start方法:

    KeyGenerator().start() 
    
    # or 
    
    key_gen = KeyGenerator() 
    key_gen.start() 
    
+0

非常感謝! – Number28

0

你有兩個問題:

  1. 你在每類功能錯過壓痕
  2. 你必須創建該類的對象,然後才能調用其任何功能

您R類別應該是這樣的

import random 

class KeyGenerator(): 
    def __init__(self): 

     length = 0 
     counter = 0 
     key = [] 
     Letters = ['a','b','c','d','e'] 

    def KeyGen4(self): 
     while self.counter != self.length: 
      a = random.choice(self.Letters) 
      print a #test 
      r = (random.randint(0,1)) 
      print r #test 
      if r == True: 
       a = a.upper() 
      else: 
       pass 
      self.key.append(a) 
      self.counter += 1 

     s = ''  
     self.key = s.join(key) 
     print self.key 
     return self.key 

    def start(self): 
     selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >') 

     if selection == 'K' or 'k': 
      length = 4 
     self.keyGen4() 

     elif selection == 'N' or 'n': 
      self.KeyGenN() 

     elif selection == 'C' or 'c': 
      length = int(raw_input("Key Length: ")) 
     #KeyGen4(self) # Change later after creating method with more options 

#now make an instance of your class 
my_key_gen = KeyGenerator() 
my_key_gen.start() 

請注意,調用類的內部類的功能時,你需要使用self.FUNCNAME。所有的類功能應該以「自我」作爲參數。如果這是他們唯一的說法,那麼你只需撥打self.func()即可。如果他們採取論據,你仍然省略自己,因爲self.func(arg1, arg2)

+0

我讚賞冗長的迴應!我忘了做這個班的一個實例......我需要多讀一些,所以我可以記住這些東西。謝謝! – Number28