Search code examples
classmethodspython-3.7initself

Why use __init__ and self when we can use simple methods


I am having confusion as to why do we use init and self while defining a class when we can use methods. The following example illustrates my confusion:

Example 1 Utilizing init and self:

class car:
    def __init__(self,model,color):
        self.model = model
        self.color = color
    def show(self):
        print('model is', self.model)
        print('color is', self.color)    

audi = car('audi a4', 'blue')
ferrari = car('ferrari 488','green')

audi.show()
model is audi a4
color is blue

ferrari.show()
model is ferrari 488
color is green

Example 2 Utilizing methods:

class car:
    def audifeatures(car, model, color):
        print ('car is', car, 'model is', model, 'color is', color)
    def ferrarifeatures(car, model, color):
        print ('car is', car, 'model is', model, 'color is', color)

car.audifeatures('audi','x8','black')
car is audi model is x8 color is black

car.ferrarifeatures('ferrari','f5','red')
car is ferrari model is f5 color is red

Solution

  • The phrase "car is audi model is x8 color is black" generated by your print statement is just words; you're simply forming a string that uses the words "model" and "color" (and the car class is basically irrelevant).

    init and self is about defining an object with properties so that you can do object-based programming; the car class generates an instance that actually has a model and a color.

    It's like the difference between a parrot that repeats the phrase "I am six feet tall" and a human being who actually is six feet tall.