Search code examples
pythonprogram-entry-point

Name Error when running a Python Script


My code is

class GuessPassword(object):
      def generate_Parent(self,length):
              genes= []
              while len(genes) < length:
                   sampleSize = min(length - 
                       len(genes),len(self.__class__.geneSet))         
                   genes.extend(random.sample(self.__class__.geneSet, 
                              sampleSize))
             return ''.join(genes)

In My main method

if __name__ == '__main__':
   random.seed()
   bestparent = self.generate_Parent( len(target))

and it's giving the error "NameError: name 'self' is not defined". And when I ran it without "self" it gave the error "NameError: name 'generate_Parent' is not defined".

I know it's a small issue. But I searched and couldn't find a solution. Any help would be great.


Solution

  • You use self out of the class, also you need to make an object of the GuessPassword class, if you want to use class methods.

    if __name__ == '__main__':
       random.seed()
       # bestparent = self.generate_Parent( len(target)) # here is error
    
       # make object of a class
       guess = GuessPassword()
       # remove `self` because you are not in a class, and use object instance
       bestparent = guess.generate_Parent( len(target))