Skip to content

Commit e77febf

Browse files
committed
getitem and setitem
1 parent d8c62b7 commit e77febf

File tree

2 files changed

+167
-1
lines changed

2 files changed

+167
-1
lines changed
+165
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "b3c0145c",
6+
"metadata": {},
7+
"source": [
8+
"# Python: Everything\n",
9+
"- 24) **Magic methods, __getitem__ and __setitem__:** These methods may be implemented in a class to override the default ones for indexing and assignment, respectively.\n",
10+
"<br>----------------------------------------------\n",
11+
"<br> https://www.pinterest.com/HamedShahHosseini/programming-languages/\n",
12+
"<br>https://github.com/ostad-ai/Python-Everything"
13+
]
14+
},
15+
{
16+
"cell_type": "markdown",
17+
"id": "35474859",
18+
"metadata": {},
19+
"source": [
20+
"Let's apply **indexing** to a list."
21+
]
22+
},
23+
{
24+
"cell_type": "code",
25+
"execution_count": 1,
26+
"id": "2191568a",
27+
"metadata": {},
28+
"outputs": [
29+
{
30+
"name": "stdout",
31+
"output_type": "stream",
32+
"text": [
33+
"The list: [2, 3, 5, 7, 11, 13]\n",
34+
"List item at index 2 using indexing:5\n",
35+
"List item at index 2 using getitem:5\n",
36+
"--------------------\n",
37+
"The dictionary: {'one': 'hello', 'two': 'world', 'three': 'bye'}\n",
38+
"Dict. value at key two, using keying: world\n",
39+
"Dict. value at key two, using getitem: world\n"
40+
]
41+
}
42+
],
43+
"source": [
44+
"# both self[key] and self.__getitem__(key) are the same\n",
45+
"primes=[2,3,5,7,11,13]\n",
46+
"dicts={'one':'hello','two':'world','three':'bye'}\n",
47+
"i=2; dkey='two'\n",
48+
"print(f'The list: {primes}')\n",
49+
"print(f'List item at index {i} using indexing:{primes[i]}')\n",
50+
"print(f'List item at index {i} using getitem:{primes.__getitem__(i)}')\n",
51+
"print('--------------------')\n",
52+
"print(f'The dictionary: {dicts}')\n",
53+
"print(f'Dict. value at key {dkey}, using keying: {dicts[dkey]}')\n",
54+
"print(f'Dict. value at key {dkey}, using getitem: {dicts.__getitem__(dkey)}')"
55+
]
56+
},
57+
{
58+
"cell_type": "markdown",
59+
"id": "8d2a1b9c",
60+
"metadata": {},
61+
"source": [
62+
"Defining **getitem** method in a class to use indexing on the class instances."
63+
]
64+
},
65+
{
66+
"cell_type": "code",
67+
"execution_count": 2,
68+
"id": "4d6eeae4",
69+
"metadata": {},
70+
"outputs": [
71+
{
72+
"name": "stdout",
73+
"output_type": "stream",
74+
"text": [
75+
"Student Jim is 27\n"
76+
]
77+
}
78+
],
79+
"source": [
80+
"# we define __getitem__ in our class\n",
81+
"class Students:\n",
82+
" def __init__(self,name,age):\n",
83+
" self.records={name: age}\n",
84+
" def __getitem__(self,key):\n",
85+
" return self.records[key]\n",
86+
"name,age='Jim',27\n",
87+
"std=Students(name,age)\n",
88+
"# now we can get an item from the instance by instance[key]\n",
89+
"print(f\"Student {name} is {std[name]}\")"
90+
]
91+
},
92+
{
93+
"cell_type": "markdown",
94+
"id": "e5eece6b",
95+
"metadata": {},
96+
"source": [
97+
"Defining **setitem** method in a class which gets *key* and *value* as its arguments, to use assigment in the class instances."
98+
]
99+
},
100+
{
101+
"cell_type": "code",
102+
"execution_count": 3,
103+
"id": "07a58317",
104+
"metadata": {},
105+
"outputs": [
106+
{
107+
"name": "stdout",
108+
"output_type": "stream",
109+
"text": [
110+
"Jim is 27 years old with major CS\n",
111+
"Julia is 21 years old with major EE\n",
112+
"Smith is 32 years old with major CS\n"
113+
]
114+
}
115+
],
116+
"source": [
117+
"# we define both __getitem__ and __setitem__ in our class\n",
118+
"class Students2:\n",
119+
" def __init__(self,name,age_major):\n",
120+
" self.records={}\n",
121+
" self.records[name]=age_major\n",
122+
" def __getitem__(self,key):\n",
123+
" return self.records[key]\n",
124+
" def __setitem__(self,key,value):\n",
125+
" self.records[key]=[value[0],value[1]]\n",
126+
"name,age_major='Jim',[27,'CS']\n",
127+
"std2=Students2(name,age_major)\n",
128+
"# now we can assign items by instance[key]=value\n",
129+
"std2['Julia']=[21,'EE']\n",
130+
"std2['Smith']=[32,'CS']\n",
131+
"for key in std2.records.keys():\n",
132+
" print(f'{key} is {std2[key][0]} years old with major {std2[key][1]}')"
133+
]
134+
},
135+
{
136+
"cell_type": "code",
137+
"execution_count": null,
138+
"id": "22275727",
139+
"metadata": {},
140+
"outputs": [],
141+
"source": []
142+
}
143+
],
144+
"metadata": {
145+
"kernelspec": {
146+
"display_name": "Python 3 (ipykernel)",
147+
"language": "python",
148+
"name": "python3"
149+
},
150+
"language_info": {
151+
"codemirror_mode": {
152+
"name": "ipython",
153+
"version": 3
154+
},
155+
"file_extension": ".py",
156+
"mimetype": "text/x-python",
157+
"name": "python",
158+
"nbconvert_exporter": "python",
159+
"pygments_lexer": "ipython3",
160+
"version": "3.8.10"
161+
}
162+
},
163+
"nbformat": 4,
164+
"nbformat_minor": 5
165+
}

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,5 @@
2222
20) Exercise: Factorial for non-negative integer and float numbers with *gamma* and *factorial* function of *math module*.
2323
21) SQLite3 module, introduction: We can use *sqlite3* module in Python for creating and accessing databases without the need to have a separate server. Here, we use basic commands of **SQL** for such purposes. For example, for creating and manipulating tables in our database.
2424
22) Operator overloading in Python: Using built-in operators, it is possible to change their behaviors via implementing their relevant special methods in a custom class definition. Here, we implement operator == for almost-equal. Also, we implement operator + for vector summation.
25-
23) Lambda expressions: We may use lambda keyword to define anonymous functions. Here, we define the syntax for lambda expressions, and then we bring some applications.
25+
23) Lambda expressions: We may use lambda keyword to define anonymous functions. Here, we define the syntax for lambda expressions, and then we bring some applications.
26+
24) Magic methods, __getitem__ and __setitem__: We review getitem and setitem methods that may be used for **indexing** and **assignment** on instances of a class, respectively.

0 commit comments

Comments
 (0)