Argument self meaning


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/classes/exercises/modifying-member-variables?action=lesson_resume&link_content_target=interstitial_undefined

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
What does self exactly do please?

I know in theory that the class use self to define itself. But in the below situation, in drive_car(self) method, I used condition = 'used' (which error), instead of self.condition = 'used'. Because we already have condition = 'new stands alone without self.condition on line 2.

In brief, self.blahblah appears so arbitrarily to me…

Please help

```python

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))

def drive_car(self):
self.condition = ‘used’

my_car = Car(“DeLorean”, “silver”, 88)

print my_car.condition
my_car.drive_car()
print my_car.condition

<do not remove the three backticks above>

#2

Hi @arrayninja24186,

Because self is the first parameter in this method header …

  def drive_car(self):

… it will refer to the instance of Car from which the drive_car method is called whenever that method is called. For example, during this call …

my_car.drive_car()

self refers to the same object as my_car. Within the method, this statement creates an instance variable for my_car named condition, and assigns it the value 'used'

    self.condition = ‘used’

However, this statement that precedes the __init__ method header defines condition as a class variable, since it does not reside within any method …

  condition = "new"

Only one copy of that variable exists for the Car class and all its instances. It is not the same variable as the instance variable that has the same name.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.