Python - 类 - 自定义

时间:2016-07-10 08:27:36

标签: python class self

下面我试图将一个简单的Keygen作为第一个项目。在某个地方,我收到的错误是Self尚未定义。

我猜它可能很容易

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) 

2 个答案:

答案 0 :(得分:4)

  1. 你的缩进是错误的,但我认为这只是一个复制粘贴的问题。

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

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

答案 1 :(得分:0)

你有两个问题:

  1. 你错过了每个课堂功能的缩进
  2. 您必须先创建该类的对象,然后才能调用其任何函数
  3. 你的课应该是这样的

    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。所有课程功能都应该采用自我和#34;作为论点。如果这是他们唯一的参数,那么您只需使用self.func()来调用它们。如果他们接受了争论,你仍然会将自己遗漏为self.func(arg1, arg2)