Files
misc/python/atms-310/notebooks/Week 05 F-2.ipynb
2025-07-02 00:07:49 -07:00

329 lines
11 KiB
Plaintext
Executable File

{
"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
}