-1
class Sink:
    def __init__(self, basin, nozzle):
        self.basin = basin
        self.nozzle = nozzle

Why we use or need __init__ method? Why it isn't the same as the code below?

class Sink:
    self.basin = basin
    self.nozzle = nozzle
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
A.Papuccu
  • 57
  • 1
  • 7

1 Answers1

1

Reference : micropyramid : init is contructor

The function of init is for constructing inside of the class. That website is explained the purpose of init

"init" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.

Example of using init inside class :

class Animal(object):
      def __init__(self, atype, avoice):
          self.type = atype
          self.voice = avoice
      
      def set_type(self):
          #do something in here about type
          if type == "cat":
             return "cat is like walk"
          else:
             return self.type+"is like walk"

      def set_voice(self):
          #do something in here similar with def type
Subhanshuja
  • 390
  • 1
  • 3
  • 20