Home > OS >  difference between instance variables and global variables declared in __init__ function
difference between instance variables and global variables declared in __init__ function

Time:11-13

class Car(object):
    def __init__(self):
        self.color = 'red' #var1
        global color 
        color= 'red' #var2

What is the difference between the first and the second variable?

CodePudding user response:

Consider this code:

color = 'blue' 

class Car(object):
    def __init__(self):
        self.color = 'green'
        global color 
        color= 'red'

print(color)       # prints blue
car = Car()
print(car.color)   # prints green
print(color)       # prints red
  • Related