Python 3: Object, ID, Type
Object ID
Every object has a id. it's a unique number of current session, based on memory address.
# sample id values print(id(3)) # 137396032 print(id(4)) # 137396048 print(id("3")) # 3070494944 print(id("")) # 3070685728
Object Type
Every object has a type.
print(type(4)) # <class 'int'> print(type(4.2)) # <class 'float'> print(type("3")) # <class 'str'> print(type( [3, 4, 5] )) # <class 'list'> print(type( (3, 4, 5) )) # <class 'tuple'> print(type(type(4))) # <class 'type'>
Testing If Objects Are Identical
is
operator tests if two objects have the same ID.
print(3 is 4) # False print(3 is 3) # True print("7" is "7") # True
Object Value
Every object has a value. (here, the value means python's internal value, not what you see when you call print()
.)
print(id([3, 4])) # 3069953132 (note: id may not be the same for you) print(id([3, 7])) # 3069953132 # from the output, you can see that [3, 4] and [3, 7] were the same object, yet the value changed # all python object has value. # here, “value” doesn't mean a variable's value, but internal value of python object # 3 is a object print(3) # The value of the object 3 represents the math idea 3, in python's guts. # The value of the object 3 cannot be changed. # array is a object print([3, 4]) # [3, 4] # its values is a container to 2 other python objects, 3 and 4
Mutable vs Immutable Objects
Object are said to be “mutable” or “immutable”.
- mutable object = the object's value can change.
- immutable object = the object's value can NOT change.
Example of mutable object: List.
Example of immutable object: String, Tuple.
# mutable objects (For example, lists, dictionary) may have the same value, but are not same object print([3,4] is [3,4]) # False aa = [3, 4] bb = [3, 4] print(aa is bb) # False # here, aa and bb are same object. aa = [3, 4] bb = aa print(aa is bb) # True # changing aa also change bb, because they are same object aa[0] = "x" print(bb) # ['x', 4]