Search code examples
pythonclassself

Python - Classes - Self Not Defined


Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.

I'm guessing it's probably something easy

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) 

Solution

    1. Your indention is wrong, but I assume this is only a copy-pasting issue.

    2. That start(self) at the bottom doesn't make sense,
      and indeed self is not defined there. You should create an instance of the class, and then call its start method:

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