[Tutor] def __init__(self):

Steven D'Aprano steve at pearwood.info
Tue Apr 26 19:42:43 EDT 2016


On Tue, Apr 26, 2016 at 12:31:28PM +0530, Santanu Jena wrote:
> Hi,
> 
> Pls let me why
> "
> def __init__(self):
> 
> "
> declaration required, what's the use of this one.Pls explain  me in
> details.

Let's say that you have a class with a method:

# A talking bird, says "Polly wants a cracker" (or some other name).
class Parrot:
    def talk(self):
        message = "%s wants a cracker!" % self.name
        print(message)


Now that we have the class, we need to create at least one individual 
parrot. So we can say:

polly = Parrot()  # create an instance of the class
polly.name = "Polly"
polly.talk()
# => prints "Polly wants a cracker!"

my_parrot = Parrot() # makes a second instance, a new parrot
my_parrot.talk()  # oops, we forgot to give it a name
# => raises AttributeError, instance has no attribute "name"

This is bad, because we might forget to set all the attributes of the 
instance and prepare it for use. With just one thing to set, the name, 
it is not too bad, but imagine if there were twenty things that needed 
to be done:

my_parrot.name = "Peter"
my_parrot.colour = "red"

and so on. Fortunately, there is an alternative.

When you create an instance by calling the class:

my_parrot = Parrot()

Python will call the special method "__init__" if it exists. This 
special method is called the "initialiser" or sometimes "constructor", 
because it is used to initialise the instance. We can give it arguments, 
and have it set up the instance's attributes:

class Parrot:
    def __init__(self, name, colour="blue"):
        self.name = name
        self.colour = colour
    def talk(self):
        message = "%s wants a cracker!" % self.name
        print(message)


polly = Parrot("Polly")  # uses the default colour "blue"

my_parrot = Parrot("Peter", "red")


Python will automatically call the __init__ methods, which sets the name 
and colour attributes, so that the talk() method will work.



-- 
Steve


More information about the Tutor mailing list