1

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()
2
  • 4
    Because there is no requirement that that argument be called self. Commented Nov 25, 2016 at 5:52
  • c1.cost() is just syntactic sugar for car.cost(c1), so c1 is just an argument and like any argument can be called anything. It is just convention that this argument is called self. Commented Nov 25, 2016 at 5:59

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.