Okay, let's take it from the top. First, toss out the three lines,
model = ""
color = ""
mpg = 0
They are not needed.
Start with a class header, making your class inherit from
Now indent, and fill in the class variable(s):
condition = "good"
Notice that class variables are not written inside the init method.
Next, at the same level of indent, write the
__init__ method with
self, and the other three parameters.
def __init__(self, model, color, mpg):
Now at another level of indent, write the three instance variables:
self.model = model
self.color = color
self.mpg = mpg
Those three lines will assign the init parameter values to the instance variables.
That's the complete class definition. Now with no indentation, (in global scope) we create an instance of the class, passing in the three arguments in the order in which the init method expects them.
my_car = Car("DeLorean", "silver", 88)
At this point, we may now query or even modify the variables.
self? Loosely described, it is an object of the class that starts out empty, but then gets populated with the members created, both class and instance variables. It belongs to
class so we must past it in to the
__init__ method so it can be accessed. Note that
condition is defined directly on the class, not on the instance. That is why it has no
In simple terms,
self is often referred to as the, context object since each instance will have its own context. Context is sort of like closure around each instance that sets one instance apart from another.
my_car is one context,
your_car (assuming it is created) would be another.
When accessing instance or class variables, we must always name the context,