pythoninit

Python Class __init__ Confirmation


I'm trying to understand Python classes. I am a little confused around defining the __init__. If I have 4 functions created all taking various input variables. Do I have to assign each variable in the __init__?

 class Thing:
     def __init__(self, arguments, name, address, phone_number, other):
         self.arguments = arguments
         self.name = name
         self.address = address
         self.phone_number = phone_number
         self.other = other

     def First(self, name):
         print self.name

     def Arguments(self, arguments):
         print self.arguments

     def Address(self, address, phone_number):
         print self.address + str(self.phone_number)

     def Other(self, other):
         print self.other

I have been reading various books (Learning Python The Hard Way, Python For Beginners) and been reading various tutorials online but none of them actually confirm "You must add every variable in the init function". So any help understanding the __init__ a little better would be appreciated.


Solution

  • Firstly: The __init__() function is special in that it is called for you while creating a new instance of a class. Apart from that, it is a function like any other function, you can even call it manually if you want.

    Then: You are free to do what you want with the parameters passed to a function. Often, the parameters passed to __init__() are stored inside the object (self) that is being initialized. Sometimes, they are used in other ways and the result then stored in self, like passing a hostname and using that to create a socket - you then only store the socket. You don't have to do anything with the parameters though, you can ignore them like you do in your First() function, which receives a parameter name which is ignored. Note that this parameter name and the similar attribute self.name are different things!

    Notes: