Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

How to : What are python class variables ?

In Python we have class variables, they are not defined in any methods. They are defined at class level. The only advantage of a class variable is it stays with class. If you instantiate your class and created an object, still with object you can access the class_variable.

In [1]: class A(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         A.class_var = 20
   ...: 

In [2]: a = A()

In [3]: a.class_var
Out[3]: 20

In [4]: A.class_var
Out[4]: 20
But if you use self and defined another variable with same name, then you will have two variables. You can still access using class and another you can access using your new object.

In [5]: class B(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         self.class_var = 40
   ...: 

In [6]: b = B()

In [8]: b.class_var
Out[8]: 40

In [9]: B().class_var
Out[9]: 40

In [10]: B.class_var
Out[10]: 10

In [11]: 
  
The sample code and outputs, hope they will help you understand their flow. Thank you. Raja G

Python Object reference well explained with list

Assume you have a list and you want to make exact copy of the list.

What command you will use in python to copy a list from another list.

I used List1=List2 and List1 got copied as exactly as List2 but what happen internally is they have shared command object reference location.

Dont believe ? then lets try and try to see both lists location with id function id()

I mean do as  id(List1) and id(List2) , you will find command location for these two which means they are sharing common location and what ever operations you do they will reflect on both lists.And this is completely harmful and dangerous.

So to avoid this list copying can be done in other methods where two list will have two different object locations.

They are

list2=copy.copy(list1)
(or)
list2=list1[:]
(or)
list2=list(list1)

and for more information about object reference understanding in python I recommend you to read these

http://stackoverflow.com/questions/36244451/how-to-program-python-variable-to-point-different-reference-location-but-same-va/36244490#36244490

http://www.python-course.eu/python3_variables.php