summaryrefslogtreecommitdiff
path: root/python/atms-310/notebooks/Week 05 F-2.ipynb
blob: 1a68afc78a55c99030dfd29fdd5ca3363b1c7cc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1>12. Defining Classes And More...</h1>\n",
    "<h2>10/27/2023</h2>\n",
    "\n",
    "<h2>12.0 Last Time...</h2>\n",
    "<ul>\n",
    "    <li><b>Objects</b> have attributes and methods associated with them that can be listed using <b>dir()</b>.</li>\n",
    "    <li>Methods for strings include <b>upper()</b>, <b>isupper()</b>, <b>count()</b>, <b>title()</b>, etc.</li>\n",
    "    <li>Methods for arrays include <b>reshape()</b>, <b>ravel()</b>, <b>round()</b>, etc.</li>\n",
    "</ul>\n",
    "\n",
    "<h2>12.1 Defining A Class: The Theory</h2>\n",
    "\n",
    "We talked about how all objects are instances of a class. Using <b>dir()</b> in the previous lecture, we saw the list of attributes and methods for the <b>string</b> and <b>array</b> classes. But just as you sometimes want to create your own functions depending on your application, sometimes you want to create your own classes!\n",
    "\n",
    "This is going to get a little abstract, so bear with me while we go through this in text form - we'll soon be looking and writing plenty of our own examples! This is complex and a little hard to think about because we're actually messing with the way Python works at a more fundamental level rather than just applying it.\n",
    "\n",
    "Similar to the <b>def</b> statement for functions, creating a new class involves a <b>class</b> statement. The indented block after this class statement constitutes the definition of the class.\n",
    "\n",
    "Inside your definition, to make life easier, you just refer to the instance of the class as <b>self</b>. For example, if you want an attribute called <b>data</b>, within the class definition it will be called <b>self.data</b>.\n",
    "\n",
    "Methods are defined the same way we've been talking about functions: with a <b>def</b> statement. Each method will have a set of arguments, just the way functions normally do. The first argument in a method when defining a new class is generally going to just be the word <b>self</b>, which essentially means \"take everything we have thus far and make use of it in what follows\". This is an argument you won't have to type in when you're actually <i>using</i> the method; it's just for behind-the-scenes work.\n",
    "\n",
    "Typically, your first method will be called <b>\\_\\_init\\_\\_</b> (remember, the double-underscores indicate a fundamental method in a given class!). Every time you create an instance of your new class (for example, every time you create a string as an instance of the string class), this \\_\\_init\\_\\_ method will be called. \"Init\" stands for \"initialization\"; this is where you put any important information you'll need when creating a new instance of a class. \n",
    "\n",
    "Okay, this has been a lot. Let's see it in action!\n",
    "\n",
    "<h2>12.2 Defining A Class: The Code</h2>\n",
    "\n",
    "Let's define a class that's called simply <b>Book</b>.\n",
    "\n",
    "If we have a bunch of information associated with a book (its author, publisher, title, etc.), we can store it as an instance of the class Book. Rather than having it be a string or a list or a dictionary, it will just be called a Book. We can then come up with some helpful methods that will define what we can do to Books.\n",
    "\n",
    "Let's start our class definition. We use the word <b>class</b>, followed by the name of our class (by convention, they're typically capitalized). We then put the word <b>object</b> in parentheses; this argument is a special object that just identifies this as a class that doesn't depend on other classes. For the purposes of this course, just remember: a class definition should have the argument <b>object</b>."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Book(object):\n",
    "        \n",
    "    # We'll start by defining the method __init__.\n",
    "    # Its arguments are self, the Author's last and first names, the\n",
    "    # title, the place, the publisher, and the year.\n",
    "    def __init__(self, authlast, authfirst, title, place, publisher, year):\n",
    "            \n",
    "        \n",
    "        # We then set the convention for the rest of our class definition:\n",
    "        # the name of the object, followed by a dot, followed by\n",
    "        # the names of our various arguments.\n",
    "        self.authlast = authlast\n",
    "        self.authfirst = authfirst\n",
    "        self.title = title\n",
    "        self.place = place\n",
    "        self.publisher = publisher\n",
    "        self.year = year\n",
    "        \n",
    "    # Let's create a second method that will write a bibliography entry.\n",
    "    def write_bib_entry(self):\n",
    "            \n",
    "    # We won't need any additional arguments here, since it's all handled above.\n",
    "        return self.authlast + ',' + self.authfirst + ',' + self.title + ',' + self.place + ',' + self.publisher + ',' + self.year  \n",
    "\n",
    "\n",
    "        # We could create intermediate steps here, but let's just return the final answer.\n",
    "    # def make_authoryear(self):\n",
    "        # return self.authoryear + ' (' + self.year + ')'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have created our new class (<b>Book</b>), we can try creating some instances of the class!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.Book object at 0x10dd78110>\n",
      "the evidential power of booty\n"
     ]
    }
   ],
   "source": [
    "booty = Book(\"Dubious\", \"Thomas\", \"the evidential power of booty\", \"sanfran\", \"lava press\", \"1999\")\n",
    "print(booty)\n",
    "print(booty.title)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2003\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['__class__',\n",
       " '__delattr__',\n",
       " '__dict__',\n",
       " '__dir__',\n",
       " '__doc__',\n",
       " '__eq__',\n",
       " '__format__',\n",
       " '__ge__',\n",
       " '__getattribute__',\n",
       " '__getstate__',\n",
       " '__gt__',\n",
       " '__hash__',\n",
       " '__init__',\n",
       " '__init_subclass__',\n",
       " '__le__',\n",
       " '__lt__',\n",
       " '__module__',\n",
       " '__ne__',\n",
       " '__new__',\n",
       " '__reduce__',\n",
       " '__reduce_ex__',\n",
       " '__repr__',\n",
       " '__setattr__',\n",
       " '__sizeof__',\n",
       " '__str__',\n",
       " '__subclasshook__',\n",
       " '__weakref__',\n",
       " 'authfirst',\n",
       " 'authlast',\n",
       " 'place',\n",
       " 'publisher',\n",
       " 'title',\n",
       " 'write_bib_entry',\n",
       " 'year']"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "butt = Book(\"martelli\",\"alex\",\"py in nutshell\",\"place in CA\", \"autoparts\",\"2003\")\n",
    "print(butt.year)\n",
    "dir(butt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's pretty useful! Let's do a few exercises...\n",
    "\n",
    "<h2>12.3 Book Class Exercises</h2>\n",
    "\n",
    "After running the code above, answer the following questions:\n",
    "\n",
    "<b>1. How would you print out the authorfirst attribute of the pynut instance?</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Thomas\n"
     ]
    }
   ],
   "source": [
    "print(booty.authfirst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<b>2. How would you print the full bibliography entry for the beauty instance?</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dubious,Thomas,the evidential power of booty,sanfran,lava press,1999\n"
     ]
    }
   ],
   "source": [
    "print(booty.write_bib_entry())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<b>3. How would you change the publication year for the beauty instance to \"2010\"?</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2010\n"
     ]
    }
   ],
   "source": [
    "booty.year = \"2010\"\n",
    "print(booty.year)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2>12.4 Further Class Exercises</h2>\n",
    "\n",
    "<b>1. Create another instance of the Book class using a book of your choosing (or get creative and make something up!). Check to make sure it looks okay using the write_bib_entry() method.</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "butt,booty,balls,leftcheek,rightcheek,9090\n"
     ]
    }
   ],
   "source": [
    "ass = Book(\"butt\", \"booty\", \"balls\", \"leftcheek\", \"rightcheek\", \"9090\")\n",
    "print(ass.write_bib_entry())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<b>2. Add a method called make_authoryear to the class definition. This method will create an attribute called authoryear and will set it to a string composed of the author's name followed by the year of publication in parentheses: </b>Dubay (1999)<b>, for instance. This method should not have a return statement, but should instead use a line starting with </b>self.authoryear = <b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2>12.5 Take-Home Points</h2>\n",
    "<ul>\n",
    "    <li>A class can be created using a <b>class</b> statement followed by the name of the class.</li>\n",
    "    <li>Methods within a class definition are created using a <b>def</b> statement.</li>\n",
    "    <li><b>__init__</b> is typically the first method defined and is used to initialize the core features of the class.</li>\n",
    "</ul>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}