PYTHON: UNDERSTANDING VARIABLES



When it comes to variables in OOPS we have two different types of variables. First one is a instance variable and the second one is the class variable.


                                                                             


 


 TYPES OF VARIABLES :



  • INSTANCE VARIABLES. 

  • CLASS (STATIC) VARIABLES. 


 




 


Now, lets see that what is the differenc between them, lets understand this with the example, 


class car:


def__init__(self):


self.mil=10


self.comp="BMW"


We are taking a class "car", and ofcourse every car would have certain variables like Company, Engine, Mileage. So if we want to use a variable we are using a functions __init__. Now you can define certain variables inside. We can say self.mil=10, self.comp="BMW" . Okay, now these two variables are called as INSTANCE VARIABLES. Now why is these instance because as your path changes, as the object changes this value also changes. By default the value is 10 and BMW but you can change it.


let's say, 


c1=car()


c2=car()


print(c1.comp, c1.mil)


print(c2.comp, c2.mil) 


And when we would run this piece of code, we would get the same value because they are same. but can we change the value?


Yes we can! 


c1=car()


c2=car()


c1.mil=8


print(c1.comp, c1.mil)


print(c2.comp, c2.mil) 


Now, if you run the code values will be changing. Here if you change one object no other objects would be affected.


But there are variables when changing the single variables effects the other object too. Okay, so we'll do this by defining a variable outside in it because if you create a variable inside in it, it becomes a Instance variable. If we define it outside but inside a class ofcourse, it becomes a class variable.


class car:


wheels=4


def__init__(self):


c1=car()


c2=car()


c1.mil=8


print(c1.comp, c1.mil, c1.wheel)


print(c2.comp, c2.mil, c2.wheel) 


Here wheels is common to all gthe objects every object can share the same value of it. We can use object name or class name both works. Now you want to change the value of it. As in your memory you have different namespace. Namespace- a place where you create and store object/ variable. So we have 2 namespace one for class and other object. So wheel belongs to class namespace. Okay! So if you want to modify it, you have to use a class name. And it will effect all the objects.


class car:


wheels=4


def__init__(self):


c1=car()


c2=car()


c1.mil=8


Car.wheel=5


print(c1.comp, c1.mil, c1.wheel)


print(c2.comp, c2.mil, c2.wheel) 


 



 


 


Editor: MUSKAN GUPTA Added on: 2020-05-30 17:03:04 Total View:367







Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---