Objects in Python
Introduction
The main object in Python, from which everything inherits, is PyObject
python.org
It has two attributes: the reference count
Py_REFCNT
and the type
Py_TYPE
.
You can read about iteration, iterators and iterable objects in the article
«Iteration in Python»
id()
Let us look at a function that is very useful for understanding objects further: id()
# id() print("# id():\n") a = 1961 print("a = 1961") print(f"id(a) = {id(a)}")
# id(): a = 1961 id(a) = 140042834389712
b = 1065 print("b = 1065") print(f"id(b) = {id(b)}")
b = 1065 id(b) = 140042834389648
b is a new element with its own unique id
If you run b = a, then b gets the id and the value of a, that is, it becomes the same object; the object a simply gets a second name.
b = a print("b = a") print(f"id(b) = {id(b)}") print(f"id(a) == id(b): {id(a) == id(b)}") print(f"a is b: {a is b}")
b = a id(b) = 140042834389712 id(a) == id(b): True a is b: True
In loops when the counter is increased, a new object is created.
i = 0 print("i = 0") print(f"id(i) = {id(i)}") i += 2 print("i += 2") # A new object is created print(f"id(i) = {id(i)}")
i = 0 id(i) = 140042835400976 i += 2 id(i) = 140042835401008
dir()
You can get all the attributes of an object with the function
dir()
Let us look at an ordinary
string
print("l =", l) print("m =", m)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
And now a simple list
l = ["l", "m"] print(dir(l))
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
You can see that some attributes match and some do not. For example, strings have no copy method, while lists have no upper.
Equality by value and by identity
== compares the values of objects.
is checks whether the objects are the same object in memory. That is, it compares references to an area in memory.
# Value vs. Identity Equality print("\n# Value vs. Identity Equality:\n") p = [5, 6, 7] print(f"p = {p}") q = [5, 6, 7] print(f"q = {q}") print(f"p == q: {p == q}") print(f"p is q: {p is q}") print(f"p is p: {p is p}") # Value-equality and identity equality are fundamentally # different concepts. # Comparison by value can be controlled programatically # Identity comparison is unalterable defined # by the language # Value vs. Identity Equality:
p = [5, 6, 7] q = [5, 6, 7] p == q: True p is q: False p is p: True
Mutable and immutable objects
Objects can be mutable and immutable
A very good illustration of the difference in their use is
default arguments
Set , Dictionary (dict) and List are mutable objects.
String - is an immutable object
a = "aaa" b = a b = "bbb" print("a =", a) print("b =", b)
a = aaa b = bbb
A list is a mutable object, but in this example the behaviour of the list and of the string is so far the same, because both b = "bbb" and m = ["m", "m"] create new objects.
l = ["l", "l"] m = l m = ["m", "m"] print("l =", l) print("m =", m)
l = ['l', 'l'] m = ['m', 'm']
And in the next example the difference is already visible. The original string a will stay unchanged, but the list l will change because of a change to m
a = "aaa" b = a b += "b" print("a =", a) print("b =", b) l = ["l", "l"] m = l m.append("m") print("l =", l) print("m =", m)
a = aaa b = aaab l = ['l', 'l', 'm'] m = ['l', 'l', 'm']
With the function id() you can make sure that the string b became a new object after b += "b", while the list m and the list l remained one and the same object.
In the next example we change the list not with append(), but directly, yet the result will be the same.
# Mutable Objects print("\n# Mutable Objects:\n") my_list = [0, 1, 2] print(f"my_list = {my_list}") s = my_list print("s = my_list") print(f"s = {s}") # Change an element in s # and see that the original my_list changes too s[1] = 34 print("s[1] = 34") print(f"s = {s}") # Not only s changed, but my_list as well print(f"my_list = {my_list}") print(f"s is my_list: {s is my_list}") # Python doesn't have variables in the sense of boxes # holding a value # Python has named references to objects
python objects_example.py
# Mutable Objects: my_list = [0, 1, 2] s = my_list s = [0, 1, 2] s[1] = 34 s = [0, 34, 2] my_list = [0, 34, 2] s is my_list: True
Passing arguments
m = [0, 1, 2] print(f"m = {m}") def modify(k): k.append(3) print("k =", k) print("\nmodify(m)\n") modify(m) print(f"m = {m}") print("\nNo copy of m is made\n") print("\nmodify(m)\n") modify(m) print(f"m = {m}")
m = [0, 1, 2] modify(m) k = [0, 1, 2, 3] m = [0, 1, 2, 3] No copy of m is made modify(m) k = [0, 1, 2, 3, 3] m = [0, 1, 2, 3, 3]
The function modify() works with the same object, so its values are changed. You can work around this behaviour with the function copy()
Let us look at the function replace() in which a new object is created
f = [4, 5, 6] print("f = ", f) def replace(g): g = [7, 8, 9] print("g =", g) print("\nreplace(f)\n") replace(f) print("f = ", f)
python replace.py
f = [4, 5, 6] replace(f) g = [7, 8, 9] f = [4, 5, 6]
Because the reference to the old object is not used (instead, the variable g points to a new object), the value of the variable f did not change.
You can rewrite the function replace() so that it replaces the original object.
Let us call the new function replace_contents()
def replace_contents(g): g[0] = 20 g[1] = 21 g[2] = 22 print("g = ", g) f = [10, 11, 12] print("f = ", f) print("\nreplace_contents(f)\n") replace_contents(f) print("f = ", f) # Function arguments are transferred using # pass-by-object-reference # References to objects are copied, # not the objects themselves.
python replace_contents.py
f = [10, 11, 12] replace_contents(f) g = [20, 21, 22] f = [20, 21, 22]
It is quite easy to make sure that, unless special actions are taken, the function returns the very same object
def f(d): return d c = [0, 1, 2] print("c = ", c) e = f(c) print("e = f(c)") print(f"c is e: {c is e}")
python return_semantics.py
c = [0, 1, 2] e = f(c) c is e: True
Everything is an object
Let us look at the script words.py with the following content.
"""Retrieve and print words from a URL. Usage: python3 words.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document """ # PEP 257 # story = urlopen("http://sixty-north.com/c/t.txt") story = urlopen(url) story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(story_words): """Print items one per line. Args: An iterable series of printable items. """ for word in story_words: print(word) def main(url): words = fetch_words(url) print_items(words) if __name__ == "__main__": main(sys.argv[1])
➭ python
Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import words
>>> type(words)
<class 'module'>
You can get all the attributes of an object with the function dir()
>>> dir(words)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'fetch_words', 'main', 'print_items', 'sys', 'urlopen']
>>> type(words.fetch_words)
<class 'function'>
>>> dir(words.fetch_words)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> words.fetch_words.__name__
'fetch_words'
>>> words.fetch_words.__doc__
'Fetch a list of words from a URL.\n \n Args:\n url: The URL of a UTF-8 text document.\n\n Returns:\n A list of strings containing the words from\n the document\n '
Article author: Andrei Olegovich