What is the differenace ?

D-Man dsh8290 at rit.edu
Thu Nov 16 11:42:22 EST 2000


If you are familiar with C++ or Java :

class A
{
	static int i = 1 ;
	int j ;

	A( )
	{
		this.j = 2 ;
	}
}


Egbert was correct in his explanation, but I want to clarify it a little.  The variable 'i' only has 1 copy for all instances of the class.  Although references and objects being the way they are in python it doesn't work quite the way the example C++/Java code works.  If you're not familiar with C++/Java, the 'static' keyword means that there is only 1 variable named 'i' that all instances of class A share.  In C++/Java you can perform any operations on 'i' that you would do on any int and it remains shared.  This is because C++ allocates 1 block of memory and you are modifying the memory as you please.  (I'm not sure what the Java implementation does, but I believe it has the same semantics).  

Here's a sample of my test in the interpreter:

>>> class A :
..     i = 1
..     def __init__( self ) :
..             self.j = 2 
.. 
>>> a = A()
>>> b = A()
>>> a.i
1
>>> b.i
1
>>> b.i = 3
>>> b.i
3
>>> a.i
1

since 'i' is a reference to the object 1, the assignment doesn't work like the C++/Java would have you expect

>>> class A :
..     i = [1] 
..     def __init__( self ) :
..             self.j = 2
.. 
>>> a = A()
>>> b = A()
>>> a.i
[1]
>>> b.i
[1]
>>> b.i[0] = 2
>>> b.i
[2]
>>> a.i
[2]

because the reference hasn't change, only the list contents, it works the way the C++/Java code would  (think of the list as a pointer here)

>>> b.i = [4]
>>> a.i
[2]

once again, the assignment changes the reference of only 1 of the i's

>>> dir ( A )
['__doc__', '__init__', '__module__', 'i']
>>> A.i
[2]
>>> 


To get 'i' to behave like a static variable you need it to be a reference to a reference to the data.  That way i will never change, only the reference it refers too, preserving the sharing.  Would anybody like to contribute a more elegant way that using a list as a "pointer" ?

-D


On Thu, 16 Nov 2000 03:24:32 Przemysław G. Gawroński wrote:
 | Lets say we have a class like this one:
 | 
 | class A:
 | 	i = 1
 | 	def __init__ (self):
 | 		self.j = 2
 | 
 | When I create an object of such class (lets say v), calling dir( v ) I
 | get:
 | 
 | ['j']
 | 
 | but I can also access the variable i what is the difference between them
 | ( i and j ) and why the variable i isn't listed ???
 | 
 | Thanks Przemek 






More information about the Python-list mailing list