Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

difference between instance variables and global variables declared in __init__ function

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading