{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

12. Defining Classes And More...

\n", "

10/27/2023

\n", "\n", "

12.0 Last Time...

\n", "\n", "\n", "

12.1 Defining A Class: The Theory

\n", "\n", "We talked about how all objects are instances of a class. Using dir() in the previous lecture, we saw the list of attributes and methods for the string and array 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 def statement for functions, creating a new class involves a class 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 self. For example, if you want an attribute called data, within the class definition it will be called self.data.\n", "\n", "Methods are defined the same way we've been talking about functions: with a def 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 self, 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 using the method; it's just for behind-the-scenes work.\n", "\n", "Typically, your first method will be called \\_\\_init\\_\\_ (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", "

12.2 Defining A Class: The Code

\n", "\n", "Let's define a class that's called simply Book.\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 class, followed by the name of our class (by convention, they're typically capitalized). We then put the word object 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 object." ] }, { "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 (Book), 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", "

12.3 Book Class Exercises

\n", "\n", "After running the code above, answer the following questions:\n", "\n", "1. How would you print out the authorfirst attribute of the pynut instance?" ] }, { "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": [ "2. How would you print the full bibliography entry for the beauty instance?" ] }, { "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": [ "3. How would you change the publication year for the beauty instance to \"2010\"?" ] }, { "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": [ "

12.4 Further Class Exercises

\n", "\n", "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." ] }, { "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": [ "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: Dubay (1999), for instance. This method should not have a return statement, but should instead use a line starting with self.authoryear = " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

12.5 Take-Home Points

\n", "" ] }, { "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 }