How does __init__ know what values to assign to instance variables?

Question

How does init know what values to assign to instance variables?

Answer

If we make an __init__() method that accepts the same parameters as our Car class, like this: (self, model, color, mpg), then these are the values that will be provided whenever you create a new Car object.
When a new Car object is created, the values provided as arguments for those parameters are then given to you for use inside the __init__() method. That’s where we’re able to create new instance variables with the structure: self.variable_name = variable_name. The left side uses self to tell Python to create a new instance variable for this particular object we just made, and then the right side is the value we store in that new variable, which is just the argument value.

2 Likes

class Car(object):
def intit(self, model):
self.model (1) = model #(2)
self.other = “string”
(1) tell Python that is a attribute of Car class
ex: n = Car(“MD6”)
print(n.model) >>>“MD6”
print(n.other)>>>“string”

Am I wrong?

Given the spelling error, yes. Please use markdown to format posted code samples so we can see the blocking.

2 Likes

‘In order to assign a variable to the class (creating a member variable), we use dot notation’

Doesn’t this create new instance variables, not member variables? Could this be a typo on Codecademy’s side?

Because I thought a member variable was one which didn’t differ for all instances/objects of a class? Whereas, the member variables created in the init function clearly do.

The two terms are synonymous and refer to the variables belonging to the instance. Class variables are the ones that belong to the class which all instances inherit with the same initial value. Once an instance changes the value, it becomes an instance variable.

2 Likes

Thanks! As ever, a great help

3 Likes

class Car(object):
condition = “new”
def init(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
my_car = Car(“DeLorean”, “silver”, 88)
print my_car

Why does this code output the following?: <Car object at 0x7f5930076450>
Shouldn’t it output the model name, color name, & mpg rating like:
DeLorean
silver
88

?

Python only knows that my_car is an instance of Car, not how to represent the attributes of that instance. That is why we write a __repr__() method so that there is a template.

def __repr__(self):
    return "Model: %s, Color: %s, MPG: %d" % (self.model, self.color, self.mpg)

Now when we print, we get a string.

print my_car

Model: DeLorean, Color: silver, MPG: 88
1 Like

Oh ok! Thank you again for your clear explanation!

1 Like