JKV
JKV

Reputation: 11

Code works even without 'self' attribute in method

In the class below, the self parameter in class method cost is replaced with another name 'insta' but still it works. Why?

class car():
   model='sedan'
   year=2016
   price=775000

   def cost(insta):
      print "Price of car is: ",insta.price

c1=car()
c1.model='SUV'
c1.year=2017
c1.price=120000
c1.cost()

c2=car()
c2.model='hatchback'
c2.year=2018
c2.price=600000
c2.cost()

Upvotes: 1

Views: 73

Answers (2)

hlp
hlp

Reputation: 1057

When you instantiate c1 to be an object of class car, c1 gets those 3 things (attributes) you gave it: a model, a year, and a price. In order for c1 to know that you want its cost() method to access its price and not c2's price for example, you (correctly) defined the cost() method to associate the price printed with the price of the object that cost() is called on.

The word self is common, perhaps because given Python syntax, when you call a method on a class object with dot notation as in classObject.classMethod(), it might feel more like you are "calling classMethod() on classObject" than more typically "passing someArgument to someFunction" let's say, since you don't put classObject inside the parenthesis of classMethod. But the key piece is the association you make in the class definition (which will work with "self" or "insta" or "puppy", as long as you use the chosen word consistently). Perhaps a useful naming that would help illuminate what is going on in this particular context would be

def cost(myCar):
    print ("Price of car is: ", myCar.price)

since you want the cost of myCar to be the price of myCar. This is what self does in a more general (and thus more readable and maintainable) way.

Upvotes: 0

Right leg
Right leg

Reputation: 16710

Naming self the first parameter of a class method is nothing more than a convention. Your code is strictly tantamount to:

def cost(self):
    print "Price of car is: ",self.price

However, this convention is respected everywhere, and although I knew it was only a convention, I think it's the first time I see a code not naming the instance self.

Upvotes: 4

Related Questions