For Java and C++ for example if you forget to declare a variable before you try to access it it will generate an error during compilation phase. Below is an example code in Java that illustrates this.
Java
$ javac JavaExample.java JavaExample.java:7: cannot find symbol symbol : variable number location: class JavaExample number=_number; ^ JavaExample.java:11: cannot find symbol symbol : variable number location: class JavaExample System.out.println("[test " + number + "] list=%s"); ^ 2 errorsPython
When you start applying object oriented programming paradigms in Python and start to write classes and create instances you may encounter an interesting phenomena. The code below illustrate this.
The difference between the 2 classes is that in the class Test2ClassVariable we have defined this variable self.mylist=[] additionally.
When you run this code this is the output:
$ python object_variables_example.py [test 1] list=one [test 2] list=one two [test 3] list=three [test 4] list=fourThe interesting part of the output is in line #3. The variable list has 2 entries where at first look we would expect it should have only one. Not knowing anything about objects in Python this would be a natrual intuition for everyone with Java or C++ background.
Explanation
We see this behavoiur because Python uses a concept of class and instance variables. For Java/C++ programmers a python class variable is simply a Java/C++ static class variable. In our example variable list is a class variable and it is shared between all class instances. That explains the output we see.
References
No comments:
Post a Comment