7. Problem with 'self' word


#1

Hi,

I have no idea what's wrong, what to do, what means 'tip'.
My code:

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
    def display_car(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
        print "This is a %s %s with %s MPG." %(color, model, str(mpg))
    
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.display_car("DeLorean", "silver", 88)

My output is:

new
This is a silver DeLorean with 88 MPG.
None
None

My error is:

Oops, try again.
Make sure you pass the self keyword to the display_car() method.

Yea, I tried self.color, self.model and str(self.mpg) in print statement in def display_car() and same error occurs.


#2

You do not need to assign the variables again in your class method.

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
    def display_car(self):
        print "This is a %s %s with %s MPG." %(self.color, self.model, str(self.mpg))

#3

Ok, I did as you wrote, but I totally don't get it.

  1. Why assigning variables again is incorrect?
  2. So data stored in init is 'common' for every method in class and they (methods) have access to them (data in init)?
  3. Why there is self. in print statement if self.model is "switched" to model in init?
  4. How to put code as you, I mean it is colored and stronged.

Thanks for quick reply!

EDIT: Ah, one more question - why my first code in visualizer works without errors?


#4

The most simplistic way to put it is that you are referring to the scope level of the object. When you put self you are referring to the class scope of the object that follows the self.

If we failed to refer to the class it will then look at the next higher scope and if it fails to find your reference it will crash your program.

So your code works because you created a local variable in your method by passing the same information into your class method that you instantiated your class with.

You can remember that __init__ is equivalent to being instantiated, this means that when the class is called it will build what ever information you have inside of your method.

To get your code to look like that you have to use markdown, meaning you have to do this

```python
# CODE HERE
``` # end

So in closing we use self to tell python that we are referring to the class scope so that it can properly find the information it is looking for. If we fail to tell it this information it will look at the next higher scope for this information which can result in a error.


#5

Ok, thanks for explaining, I will read this few times tomorrow to get this better.