Class Instances
Author |
Message |
Zren
|
Posted: Mon Mar 01, 2010 9:13 pm Post subject: Class Instances |
|
|
Python: | class Map:
def __init__(self, w=100, h=100):
self.w = w
self.h = h
self.camera = Camera(self.w, self.h)
self.newObject(self.camera)
self.objs = []
def newObject(self, obj):
self.objs.append( obj )
class Camera(GameObject):
def __init__(self, w=0, h=0, x=0, y=0):
GameObject.__init__(self, x, y, w, h) |
My question is that if I call self.camera and modify it's variables, would it affect the same instance of Camera as the one inside the self.objs list? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
DtY
|
Posted: Mon Mar 01, 2010 10:01 pm Post subject: RE:Class Instances |
|
|
Short; yes
Long; yes, everything in python are references. When you create a new object, it stores a reference to the newly created object in that variable.
Python: | a = [1,2,3]
b = a
b.append(5)
print a |
Because `b` and `a` are references to the same object, changing `b` changes `a`, and vice versa.
Same thing happens when calling a function, a local reference to that variable is made.
There are just two things to look out for:
Python: | a = [1,2,3]
b = a
b = [3,2,1]
print a |
This may appear to go against what I just said, but what is happening is that when you say b = [3,2,1], it is no longer a reference to `a`, it is new object (note that if you use +=, it will modify the original, not create a new object).
The exception to this is immutable types, because anything that modifies them creates a new object. The mutable types are all numerical data, booleans, tuples and strings. Anything done to these types will only effect what that variable holds, and no other references to it.
All user created types are mutable.
A cool side effect of this is that you can append a list to itself, and it will always hold itself, not just what it was holding.
Python: | >>> a = [ ]
>>> a.append(a)
>>> a
[[...]]
>>> a[0]
[[...]]
>>> a.append(0)
>>> a
[[...], 0]
>>> a[0]
[[...], 0]
>>> a[0][0][0]
[[...], 0]
>>> a[0][0][0][1]
0 |
Just to note, the ellipses in that example denote a self reference, it would fall into infinite recursion if it tried to expand it, so it's smart about it. |
|
|
|
|
|
Zren
|
Posted: Mon Mar 01, 2010 10:11 pm Post subject: RE:Class Instances |
|
|
Thanks for the last note lol, I was about to try it. And thanks for the long explanation as well. |
|
|
|
|
|
|
|