user430191
user430191

Reputation: 255

not all attributes defined in __init__?

I've seen the following code.

class Primes:    

   def __init__(self, max):       
       self.max = max        
       self.number = 1

   def __iter__(self):       
       return self

   def __next__(self):        
       self.number += 1        
       if self.number >= self.max:           
           raise StopIteration        
       elif check_prime(self.number):            
           return self.number        
       else:            
           return self.__next__()

In the dunder init function, we set self.number=1, without having included earlier the attribute number. What's the meaning of it?

Upvotes: 0

Views: 633

Answers (1)

azro
azro

Reputation: 54148

This code, only means that self.number is not customizable and will always values 1 when creating an instance of Primes. This is used when the class need an attribute, which will be used along its state and methods, but it's value should always be the same when instanciating the object

def __init__(self, max):       
    self.max = max        
    self.number = 1

Upvotes: 1

Related Questions