{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## CS 200: Object-oriented programming\n", "\n", "\n", "\n", "\n", "### Video:\n", "\n", "See Classes and Objects from Socratica.\n", "\n", "This notebook includes code from oop.py.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Principles\n", "\n", "#### Encapsulation. \n", "\n", "Python uses namespaces to achieve encapsulation. Other OOP languages have private and public data and methods. Python, not so much.\n", "\n", "#### Polymorphism. \n", "\n", "Many shapes. The same method can mean different things depending on the object on which it is invoked. Consider the install method. It means different things for a refrigerator, stove, television, alarm system, IKEA cabinet, or military dictatorship." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "What is depicted above?\n", "\n", "#### Inheritance. \n", "\n", "OOP uses ISA hierarchy principle from cognitive psychology.\n", "\n", "- A mammal has fur and nurses its young.\n", "- A dog ISA mammal and has four legs and a tail. \n", "\n", "You may infer that a dog has fur and nurses its young.\n", "\n", "- A poodle ISA dog. \n", "\n", "You may infer that it has four legs and a tail. However, you may override defaults, e.g., a Mexican hairless dog or an amputee pooch.\n", "\n", "### Example: The course class" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class course:\n", " ''' A class for describing courses, e.g., math or computer science.'''\n", "\n", " # class variables\n", " count = 0\n", " classes = [] ## gratuitous confusion.\n", "\n", " \n", " def __init__(self, title, dept):\n", " ''' \n", " This is an example of function overloading.\n", " The constructor which sets the initial values of the course title and department.\n", " We increment the class variable for count and add the new instance to the classes list.\n", " We set default values for the instance variables:\n", " students, room, hours, and prereqs.\n", " '''\n", " # instance variable\n", " ## code below did not handle inheritance class variable correctly\n", " ## self.count = self.__class__.count\n", " self.count = course.count\n", " # self.__class__.count += 1\n", " course.count += 1\n", " \n", " ## same problem as above\n", " ## self.__class__.classes.append(self)\n", " course.classes.append(self)\n", " self.title = title\n", " self.dept = dept\n", " self.students = []\n", " self.room = ''\n", " self.hours = ''\n", " self.prereqs = []\n", "\n", " def __repr__(self):\n", " ''' Display an object so it can be evaluated and created.'''\n", " return '\"course({}, {!r})\"'.format(repr(self.title), self.dept)\n", "\n", " def __str__(self):\n", " ''' Display an object as a string. '''\n", " return \"\".format(self=self)\n", "\n", " ## a static method is shared by all instances.\n", " @staticmethod\n", " def all(dept=''):\n", " ''' A static method is shared by all instances. \n", " It is invoked with the class name', e.g., course.all()\n", " '''\n", " for c in course.classes:\n", " if dept:\n", " if c.dept == dept:\n", " print (c)\n", " else:\n", " print (c)\n", "\n", " def add_room(self, item):\n", " ''' Specify the classroom for an instance. '''\n", " self.room = item\n", "\n", "\n", " def add_student(self, item):\n", " ''' Enroll a student in the course. This method allows duplicates. '''\n", " self.students.append(item)\n", "\n", " def add_hours(self, item):\n", " ''' Specify the meeting time for the course. '''\n", " self.hours = item\n", "\n", " ## allows duplicates\n", " def add_prereqs(self, item):\n", " ''' Specify the prerequisites for the course. '''\n", " self.prereqs.append(item)\n", " \n", " def pp(self):\n", " ''' Pretty print the object. Format all the existing data elements. '''\n", " p = \"Course Title \" + self.title\n", " if self.dept: p += \"\\n\\tDepartment: {self.dept}\".format(self=self)\n", " if self.room: p += \"\\n\\tRoom: {}\".format(self.room)\n", " if self.hours: p += \"\\n\\tHours: {}\".format(self.hours)\n", " if self.students: p += \"\\n\\tStudents: {}\".format(self.students)\n", " if self.prereqs: p += \"\\n\\tPrereqs: {!s}\".format(self.prereqs)\n", " return p\n", "\n", " def all_prereqs(self):\n", " ''' Print out all the prerequsites for a given course.\n", " Note that this function uses tree recursion.\n", " '''\n", " if self.prereqs:\n", " for pr in self.prereqs:\n", " print (\"Prereq for {}: {}\".format(self, pr))\n", " pr.all_prereqs()\n", "\n", " def __eq__(self, other):\n", " ''' Two courses are equal if they have the same title and \n", " the same department.\n", " This method overloads the == operator.\n", " '''\n", " return self.title == other.title and self.dept == other.dept\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can call the help function on the course class. We see the doc strings and methods." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class course in module __main__:\n", "\n", "class course(builtins.object)\n", " | course(title, dept)\n", " | \n", " | A class for describing courses, e.g., math or computer science.\n", " | \n", " | Methods defined here:\n", " | \n", " | __eq__(self, other)\n", " | Two courses are equal if they have the same title and \n", " | the same department.\n", " | This method overloads the == operator.\n", " | \n", " | __init__(self, title, dept)\n", " | This is an example of function overloading.\n", " | The constructor which sets the initial values of the course title and department.\n", " | We increment the class variable for count and add the new instance to the classes list.\n", " | We set default values for the instance variables:\n", " | students, room, hours, and prereqs.\n", " | \n", " | __repr__(self)\n", " | Display an object so it can be evaluated and created.\n", " | \n", " | __str__(self)\n", " | Display an object as a string.\n", " | \n", " | add_hours(self, item)\n", " | Specify the meeting time for the course.\n", " | \n", " | add_prereqs(self, item)\n", " | Specify the prerequisites for the course.\n", " | \n", " | add_room(self, item)\n", " | Specify the classroom for an instance.\n", " | \n", " | add_student(self, item)\n", " | Enroll a student in the course. This method allows duplicates.\n", " | \n", " | all_prereqs(self)\n", " | Print out all the prerequsites for a given course.\n", " | Note that this function uses tree recursion.\n", " | \n", " | pp(self)\n", " | Pretty print the object. Format all the existing data elements.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | all(dept='')\n", " | A static method is shared by all instances. \n", " | It is invoked with the class name', e.g., course.all()\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | __hash__ = None\n", " | \n", " | classes = []\n", " | \n", " | count = 0\n", "\n" ] } ], "source": [ "help(course)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Terminology\n", "\n", "#### Class:\n", "\n", "A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.\n", "
\n",
    "class course: \n",
    "
\n", "\n", "#### Class variable:\n", "\n", "A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.\n", "
\n",
    "count = 0\n",
    "classes = []\n",
    "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "#### Data member:\n", "\n", "A class variable or instance variable that holds data associated with a class and its objects.\n", "
\n",
    "count = 0\n",
    "self.count = self.__class__.count ## this does not handle inheritance properly.\n",
    "or\n",
    "self.count = course.count\n",
    "
\n", "\n", "#### Function overloading:\n", "\n", "The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved. __init__() defines the constructor for a class. Here, course() creates a new course instance.\n", "\n", "
\n",
    "def __init__(self, title, dept):\n",
    "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Instance variable:\n", "\n", "A variable that is defined inside a method and belongs only to the current instance of a class.\n", "
\n",
    "self.title = title\n",
    "
\n", "\n", "#### Inheritance:\n", "\n", "The transfer of the characteristics of a class to other classes that are derived from it" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### gradcourse inherits from course\n", "\n", "Note that help() function includes the inherited methods." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "class gradcourse(course):\n", " ''' The graduate course class inherits from the course class. '''\n", " def __init__(self, title, dept):\n", " course.__init__(self, title, dept)\n", " self.grad = True" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class gradcourse in module __main__:\n", "\n", "class gradcourse(course)\n", " | gradcourse(title, dept)\n", " | \n", " | The graduate course class inherits from the course class.\n", " | \n", " | Method resolution order:\n", " | gradcourse\n", " | course\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, title, dept)\n", " | This is an example of function overloading.\n", " | The constructor which sets the initial values of the course title and department.\n", " | We increment the class variable for count and add the new instance to the classes list.\n", " | We set default values for the instance variables:\n", " | students, room, hours, and prereqs.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from course:\n", " | \n", " | __eq__(self, other)\n", " | Two courses are equal if they have the same title and \n", " | the same department.\n", " | This method overloads the == operator.\n", " | \n", " | __repr__(self)\n", " | Display an object so it can be evaluated and created.\n", " | \n", " | __str__(self)\n", " | Display an object as a string.\n", " | \n", " | add_hours(self, item)\n", " | Specify the meeting time for the course.\n", " | \n", " | add_prereqs(self, item)\n", " | Specify the prerequisites for the course.\n", " | \n", " | add_room(self, item)\n", " | Specify the classroom for an instance.\n", " | \n", " | add_student(self, item)\n", " | Enroll a student in the course. This method allows duplicates.\n", " | \n", " | all_prereqs(self)\n", " | Print out all the prerequsites for a given course.\n", " | Note that this function uses tree recursion.\n", " | \n", " | pp(self)\n", " | Pretty print the object. Format all the existing data elements.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods inherited from course:\n", " | \n", " | all(dept='')\n", " | A static method is shared by all instances. \n", " | It is invoked with the class name', e.g., course.all()\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from course:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from course:\n", " | \n", " | __hash__ = None\n", " | \n", " | classes = []\n", " | \n", " | count = 0\n", "\n" ] } ], "source": [ "help(gradcourse)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Instance:\n", "\n", "An individual object of a certain class. An object obj that belongs to a class course, for example, is an instance of the class course.\n", "\n", "#### Examples\n", "\n", "Below we create instances by calling the constructor and instantiating course objects." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "m120 = course(\"Math 120\", \"Math\")\n", "c100 = course(\"CS100\", \"Computer Science\")\n", "c200 = course(\"CS200\", \"Computer Science\")\n", "c201 = course(\"CS201\", \"Computer Science\")\n", "c223 = course(\"CS223\", \"Computer Science\")\n", "c323 = course(\"CS323\", \"Computer Science\")\n", "c690 = gradcourse(\"CS690\", \"Computer Science\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"course('Math 120', 'Math')\"" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m120" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"course('CS200', 'Computer Science')\"" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(c200)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'CS200'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.title" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Computer Science'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.dept" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\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", " 'add_hours',\n", " 'add_prereqs',\n", " 'add_room',\n", " 'add_student',\n", " 'all',\n", " 'all_prereqs',\n", " 'classes',\n", " 'count',\n", " 'dept',\n", " 'hours',\n", " 'pp',\n", " 'prereqs',\n", " 'room',\n", " 'students',\n", " 'title']" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(c200)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.course" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.__class__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we will add more data to the objects. First, the classrooms." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "c100.add_room(\"Law School Auditorium\")\n", "c200.add_room(\"LC 101\")\n", "c201.add_room(\"LC 101\")\n", "c223.add_room(\"DL 220\")\n", "c323.add_room(\"DL 220\")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'LC 101'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.room" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, we add some students." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "c200.add_student(\"Joe\")\n", "c200.add_student(\"Mary\")\n", "c200.add_student(\"Joe\")\n", "c200.add_student(\"John\")\n", "c200.add_student(\"Jane\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Joe', 'Mary', 'Joe', 'John', 'Jane']" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.students" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we specify the pre-requisites." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "c323.add_prereqs(c223)\n", "c223.add_prereqs(c201)\n", "c201.add_prereqs(c100)\n", "c200.add_prereqs(c100)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[\"course('CS100', 'Computer Science')\"]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.prereqs" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Course Title CS200\\n\\tDepartment: Computer Science\\n\\tRoom: LC 101\\n\\tStudents: [\\'Joe\\', \\'Mary\\', \\'Joe\\', \\'John\\', \\'Jane\\']\\n\\tPrereqs: [\"course(\\'CS100\\', \\'Computer Science\\')\"]'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c200.pp()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Course Title CS200\n", "\tDepartment: Computer Science\n", "\tRoom: LC 101\n", "\tStudents: ['Joe', 'Mary', 'Joe', 'John', 'Jane']\n", "\tPrereqs: [\"course('CS100', 'Computer Science')\"]\n" ] } ], "source": [ "print(c200.pp())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The pp() method pretty prints an instance of the course class.\n", "\n", "The add_room, add_student, \n", "add_prereqs, and pp methods are instance methods. That is, they apply to a particular and specific instance of the class.\n", "\n", "By contrast, the all() method is a class method which operates over the entire class. It prints out all the instances of the course class. " ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n" ] } ], "source": [ "course.all()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The all() method has an optional dept parameter to filter the results by department." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "course.all('Math')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[\"course('CS223', 'Computer Science')\"]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c323.prereqs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The all_prereqs() method recursively lists all prereqs for a course. Below we iterate through all the course instances, pretty printing each course, and then listing the pre-requisites for CS 323." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def test():\n", " for c in course.classes:\n", " print (c.pp())\n", " print (c323.all_prereqs())" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Course Title Math 120\n", "\tDepartment: Math\n", "Course Title CS100\n", "\tDepartment: Computer Science\n", "\tRoom: Law School Auditorium\n", "Course Title CS200\n", "\tDepartment: Computer Science\n", "\tRoom: LC 101\n", "\tStudents: ['Joe', 'Mary', 'Joe', 'John', 'Jane']\n", "\tPrereqs: [\"course('CS100', 'Computer Science')\"]\n", "Course Title CS201\n", "\tDepartment: Computer Science\n", "\tRoom: LC 101\n", "\tPrereqs: [\"course('CS100', 'Computer Science')\"]\n", "Course Title CS223\n", "\tDepartment: Computer Science\n", "\tRoom: DL 220\n", "\tPrereqs: [\"course('CS201', 'Computer Science')\"]\n", "Course Title CS323\n", "\tDepartment: Computer Science\n", "\tRoom: DL 220\n", "\tPrereqs: [\"course('CS223', 'Computer Science')\"]\n", "Course Title CS690\n", "\tDepartment: Computer Science\n", "Prereq for : \n", "Prereq for : \n", "Prereq for : \n", "None\n" ] } ], "source": [ "test()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The Big Picture\n", "(from Learning Python, 5th Edition, page 1077.)\n", "The most common reasons to use Object Oriented Programming:\n", "\n", "#### Code reuse\n", "This one's easy (and is the main reason for using OOP). By supporting inheritance, classes allow you to program by customization instead of starting each program from scratch.\n", "\n", "#### Encapsulation\n", "Wrapping up implementation details behind object oriented interfaces insulates users of a class from code changes.\n", "\n", "#### Structure\n", "Classes provide new local scopes, which minimizes name clashes. They also provide a natural place to write and look for implementation code, and to manage object state.\n", "\n", "#### Maintenance\n", "Classes naturally promote code factoring, which allows us to minimize redundancy. Thanks both to the structure and code reuse support of classes, usually only one copy of the code needs to be changed.\n", "\n", "#### Consistency\n", "Classes and inheritance allow you to implement common interfaces, and hence create a common look and feel in your code; this eases debugging, comprehension, and maintenance.\n", "\n", "#### Polymorphism\n", "This is more a property of OOP than a reason for using it, but by supporting code reuse generally, polymorphism makes code more flexible and widely applicable, and hence more reusable.\n", "\n", "#### Other\n", "And, of course, the number one reason students gave for using OOP: it looks good on a resume! (OK, I threw this one in as a joke, but it is important to be familiar with OOP if you plan to work in the software field today.)\n", "Finally, ... you won't fully appreciate OOP until you've used it for a while. Pick a project, study larger examples, work through exercises -- do whatever it takes to get your feet wet with OO code; it's worth the effort.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Another example: Person class (using Hamlet))\n", "\n", "Below we import the person class from hamlet.py\n", "\n", "This had originally been a homework assignment." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Person Name hamlet\n", "\tLikes: ['fencing', 'philosophy']\n", "\tFriends: [person('horatio', 'male')]\n", "\tSiblings: [person('rocky', 'male')]\n", "\tParents: [person('gertrude', 'female'), person('King Hamlet', 'male')]\n", "\tFather: person('King Hamlet', 'male')\n", "\tMother: person('gertrude', 'female')\n", "\tUncles: [person('claudius', 'male'), person('larry', 'male')]\n", "Person Name laertes\n", "\tSiblings: [person('ophelia', 'female')]\n", "\tParents: [person('polonius', 'male')]\n", "\tFather: person('polonius', 'male')\n", "\tAunts: [person('lucy', 'female')]\n", "Person Name gertrude\n", "\tChildren: [person('rocky', 'male'), person('hamlet', 'male')]\n", "\tSons: [person('rocky', 'male'), person('hamlet', 'male')]\n", "Person Name ophelia\n", "\tSiblings: [person('laertes', 'male')]\n", "\tParents: [person('polonius', 'male')]\n", "\tFather: person('polonius', 'male')\n", "\tAunts: [person('lucy', 'female')]\n", "Person Name polonius\n", "\tSiblings: [person('lucy', 'female')]\n", "\tChildren: [person('ophelia', 'female'), person('laertes', 'male')]\n", "\tSons: [person('laertes', 'male')]\n", "\tDaughters: [person('ophelia', 'female')]\n", "Person Name horatio\n", "\tFriends: [person('hamlet', 'male')]\n", "Person Name King Hamlet\n", "\tSiblings: [person('claudius', 'male'), person('larry', 'male')]\n", "\tChildren: [person('hamlet', 'male')]\n", "\tSons: [person('hamlet', 'male')]\n", "Person Name larry\n", "\tSiblings: [person('King Hamlet', 'male')]\n", "Person Name lucy\n", "\tSiblings: [person('polonius', 'male')]\n", "Person Name rocky\n", "\tSiblings: [person('hamlet', 'male')]\n", "\tParents: [person('gertrude', 'female')]\n", "\tMother: person('gertrude', 'female')\n" ] } ], "source": [ "from hamlet import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The main class in this file is the person class." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class person in module hamlet:\n", "\n", "class person(builtins.object)\n", " | person(name, gender)\n", " | \n", " | Class for person, including friends and relatives.\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, name, gender)\n", " | Constructor for person(name, gender)\n", " | \n", " | __repr__(self)\n", " | return string that can be evaluated to recreate this instance.\n", " | \n", " | __str__(self)\n", " | String representation of person.\n", " | \n", " | add_child(self, item)\n", " | Add child to list without dulication. Add parent to child.\n", " | \n", " | add_friend(self, item)\n", " | Add friend to list without duplication. Make reciprocal.\n", " | \n", " | add_like(self, item)\n", " | Add like to list without duplication.\n", " | \n", " | add_parent(self, item)\n", " | Add parent to list without duplication. Add child to parent.\n", " | \n", " | add_sibling(self, item)\n", " | Add sibling to list without duplication. Make reciprocal.\n", " | \n", " | aunt(self)\n", " | Get aunts (female siblings of parents).\n", " | \n", " | daughter(self)\n", " | Get daughters (female children)\n", " | \n", " | father(self)\n", " | Get father (male parent).\n", " | \n", " | mother(self)\n", " | Get mother (female parent).\n", " | \n", " | pp(self)\n", " | Pretty print person.\n", " | \n", " | son(self)\n", " | Get sons (male children).\n", " | \n", " | uncle(self)\n", " | Get uncles (male siblings of parent).\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | count = 11\n", "\n" ] } ], "source": [ "help(person)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "jane = person('Jane', 'female')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "person('Jane', 'female')" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jane" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(jane)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Person Name Jane'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jane.pp()" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "jane.add_like('programming')" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Person Name Jane\n", "\tLikes: ['programming']\n" ] } ], "source": [ "print (jane.pp())" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\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", " 'add_child',\n", " 'add_friend',\n", " 'add_like',\n", " 'add_parent',\n", " 'add_sibling',\n", " 'aunt',\n", " 'children',\n", " 'count',\n", " 'daughter',\n", " 'father',\n", " 'friends',\n", " 'gender',\n", " 'likes',\n", " 'mother',\n", " 'name',\n", " 'parents',\n", " 'pp',\n", " 'siblings',\n", " 'son',\n", " 'uncle']" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(jane)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "hamlet.person" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jane.__class__" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'female'" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jane.gender" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['programming']" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jane.likes" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "john = person(\"John\", 'male')" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "john.add_friend(jane)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Person Name Jane\n", "\tLikes: ['programming']\n", "\tFriends: [person('John', 'male')]\n" ] } ], "source": [ "print (jane.pp())" ] }, { "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.10.5" } }, "nbformat": 4, "nbformat_minor": 4 }