Python - 类 - 自我未定义

Python - Classes - Self Not Defined

下面我尝试制作一个简单的注册机作为第一个项目。我在某处遇到错误,未定义自我。

我猜这可能很简单

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. 你的缩进是错误的,但我认为这只是一个复制粘贴问题。

  2. 下面那个start(self)没意义,
    确实 self 没有在那里定义。您应该创建 class 的实例,然后调用其 start 方法:

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

你有两个问题:

  1. 您错过了每个 class-函数
  2. 的缩进
  3. 您必须先创建 class 的对象,然后才能调用它的任何函数

你的 class 应该是这样的

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() 

请注意,在class中调用class函数时,需要使用self.FUNCNAME。所有 class 函数都应将 "self" 作为参数。如果那是他们唯一的论据,那么您只需用 self.func() 调用他们。如果他们接受争论,你仍然会忽略自我,因为 self.func(arg1, arg2)