Thursday, February 9, 2017

Alising

In order to solve the problem from previous post where we talked about objects and values in lists. If variable a refers to specific object in this case an object is a list of values (1, 2 ,3 ) and then we assign the variable b through command b = a to the same object then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
Reference – the association of a variable with and object. In this case there are two references to the same object.
Alised object is a type of object with more than one reference, so this object has more than one name.
If the aliased object is mutable, changes made with one alias affect the other.
>>> b[0] = 23
>>> b[1] = 23
>>> print b
[23, 23, 3]
>>> print a
[23, 23, 3]
This behavior demonstrated with previous example is sometimes useful but generally it’s safer to avoid aliasing when you are working with mutable objects.
For immutable objects like string, aliasing is not much of a problem. In this example:
>>>a = ‘Gibson’
>>>b = ‘Gibson’

It almost never makes a difference whether a and b refer to the same string or not. 

No comments:

Post a Comment