What is the Difference Between `condition` and `self.condition` Here?

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"

Why are we initially able to declare the member variable condition = without using the dot notation (line 2) but once we decide to define a method that changes the variable’s value we must use the dot notation, as such self.condition = (line 12, last line)?

member variable (like condition) and methods are automatically added to self. Its just the way its implemented in the python language.

but any time we want to access a method, instance variable or method variable inside a class we have to use self.

when programming languages are build, certain choices are made regarding the design of the language, this is the case with python. You can wonder really long about it, but its easier to just accept its the way it is

1 Like

I’m not really clear on what you mean by “added to self” in your first sentence.

I get that, just like in natural languages, sometimes it’s best not to try and understand the why and it’s better just accept the way something is, however I suppose I’m just trying to get a grasp on the pattern.

So to reiterate what you’re saying, the basic pattern to remember is that instance variables (those created in specific instances of a class) must be accessed using the dot notation, while member variables can be accessed sans dot notation?

Also, thanks for taking the time out of your day to help me understand! Very much appreciated!

the problem is that methods and member variable are added directly inside the class, here we don’t have access to self, so python adds the methods and member variable to self for us.

so that inside a method (where we do have access to self), we can actually access member variable and other methods (yes, a method can call another method) through self, given python did some magic for us.

its important to understand that self keeps track of which instance is used. Which we can demonstrate with the following example:

class Example(object):
    def __init__(self, name):
        self.name = name 

    def example_method(self):
        print self.name

x = Example("x variable")
y = Example("y variable")



when we call a method on a instance, python is handling the self parameter of the method. While if we call a method on the class itself, we need to provide the instance. Given self refers to a specific instance

Yes, its confusing, but understanding this will help you understand everything better

1 Like