Creating member variables with and without self.?


#1



For classes, what is the difference between creating a member variable condition below (which doesn't have self. part) vs. using self.condition variable in the function drive_car below? My intuitive understanding was that we set all the self. variables in the __init__ function so that it's accessible even outside that func. Since the variable condition is created outside any func/method I thought you don't need the self. part? What am I not getting 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 %d MPG." % (self.color, self.model, self. mpg)
    
    def drive_car(self):
        self.condition = "used"
        return self.condition

and a side question, when I tried the part below it gave me an error. What's the reason?

    def drive_car(self):
        return self.condition = "used"

#2

condtion is a class variable attached to every instance. When the instance refers to it in a method, it is treated as a member variable so needs a self context reference.

Since the method has access to the condition variable, the method above will have no return value, just the new assignment.

self.condition = 'used'

The error, btw is, returning a statement. We cannot return a statement, only an expression or object.


#3

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