{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# everything is an object means:\n", "# (1) everything has a type/class\n", "# (2) everything has attributes" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 100\n", "type(x) " ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 'abcd'\n", "type(x)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = [10, 20, 30]\n", "type(x)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int('123')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(123)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c', 'd']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list('abcd')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(int) " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(str)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(list)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# factory's factory = type -- every class's type is \"type\"" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(type) " ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'capitalize',\n", " 'casefold',\n", " 'center',\n", " 'count',\n", " 'encode',\n", " 'endswith',\n", " 'expandtabs',\n", " 'find',\n", " 'format',\n", " 'format_map',\n", " 'index',\n", " 'isalnum',\n", " 'isalpha',\n", " 'isdecimal',\n", " 'isdigit',\n", " 'isidentifier',\n", " 'islower',\n", " 'isnumeric',\n", " 'isprintable',\n", " 'isspace',\n", " 'istitle',\n", " 'isupper',\n", " 'join',\n", " 'ljust',\n", " 'lower',\n", " 'lstrip',\n", " 'maketrans',\n", " 'partition',\n", " 'replace',\n", " 'rfind',\n", " 'rindex',\n", " 'rjust',\n", " 'rpartition',\n", " 'rsplit',\n", " 'rstrip',\n", " 'split',\n", " 'splitlines',\n", " 'startswith',\n", " 'strip',\n", " 'swapcase',\n", " 'title',\n", " 'translate',\n", " 'upper',\n", " 'zfill']" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# a # identifier = name = variable or function.. an object of some sort\n", " # search is LEGB \n", " \n", "#a.b # .b means: Look for the name (\"attribute\") b inside of the object a\n", "\n", "a = 'abcd'\n", "dir(a) # \"dunders\" -- double underscore " ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'ABCD'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.upper()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "import os" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.sep" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "os.sep = 'hahaha'" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hahaha'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.sep " ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "os.my_course_name = 'Python objects'" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python objects'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.my_course_name" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "60" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [10, 20, 30]\n", "sum(mylist) # \"sum\" is a function, takes a list as an argument" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "# f(x)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'list' object has no attribute 'sum'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmylist\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msum\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# this will not work!\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'list' object has no attribute 'sum'" ] } ], "source": [ "mylist.sum() # this will not work!" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist.pop()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10, 20]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "# o.m()" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(mylist)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": true }, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__delitem__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__iadd__',\n", " '__imul__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__reversed__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'append',\n", " 'clear',\n", " 'copy',\n", " 'count',\n", " 'extend',\n", " 'index',\n", " 'insert',\n", " 'pop',\n", " 'remove',\n", " 'reverse',\n", " 'sort']" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(mylist)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class list in module builtins:\n", "\n", "class list(object)\n", " | list() -> new empty list\n", " | list(iterable) -> new list initialized from iterable's items\n", " | \n", " | Methods defined here:\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __delitem__(self, key, /)\n", " | Delete self[key].\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(...)\n", " | x.__getitem__(y) <==> x[y]\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __iadd__(self, value, /)\n", " | Implement self+=value.\n", " | \n", " | __imul__(self, value, /)\n", " | Implement self*=value.\n", " | \n", " | __init__(self, /, *args, **kwargs)\n", " | Initialize self. See help(type(self)) for accurate signature.\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self None -- append object to end\n", " | \n", " | clear(...)\n", " | L.clear() -> None -- remove all items from L\n", " | \n", " | copy(...)\n", " | L.copy() -> list -- a shallow copy of L\n", " | \n", " | count(...)\n", " | L.count(value) -> integer -- return number of occurrences of value\n", " | \n", " | extend(...)\n", " | L.extend(iterable) -> None -- extend list by appending elements from the iterable\n", " | \n", " | index(...)\n", " | L.index(value, [start, [stop]]) -> integer -- return first index of value.\n", " | Raises ValueError if the value is not present.\n", " | \n", " | insert(...)\n", " | L.insert(index, object) -- insert object before index\n", " | \n", " | pop(...)\n", " | L.pop([index]) -> item -- remove and return item at index (default last).\n", " | Raises IndexError if list is empty or index is out of range.\n", " | \n", " | remove(...)\n", " | L.remove(value) -> None -- remove first occurrence of value.\n", " | Raises ValueError if the value is not present.\n", " | \n", " | reverse(...)\n", " | L.reverse() -- reverse *IN PLACE*\n", " | \n", " | sort(...)\n", " | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | __hash__ = None\n", "\n" ] } ], "source": [ "help(list)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "class Foo(object):\n", " pass" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(Foo) " ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int('123')" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int()" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(123)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str()" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.Foo at 0x1102960f0>" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Foo() " ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "f = Foo()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.Foo" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(f)" ] }, { "cell_type": "code", "execution_count": 40, "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__']" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(Foo)" ] }, { "cell_type": "code", "execution_count": 44, "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__']" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(f)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "f = Foo()" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "vars() # globals() \n", "def bar():\n", " vars() # locals()\n", " \n", " " ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vars(f) " ] }, { "cell_type": "code", "execution_count": 47, "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", " 'x',\n", " 'y']" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.x = 100\n", "f.y = [10, 20, 30]\n", "\n", "dir(f)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 100, 'y': [10, 20, 30]}" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vars(f)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "g = Foo()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': {'a': 1, 'b': 2, 'c': 3}, 'b': {10, 20, 30, 40, 50}}" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g.a = {'a':1, 'b':2, 'c':3}\n", "g.b = {10, 20, 30, 40, 50}\n", "\n", "vars(g)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 100, 'y': [10, 20, 30]}" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vars(f)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "class Foo(object):\n", " def __init__(self):\n", " self.x = 100\n", " self.y = [10, 20, 30]" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 100, 'y': [10, 20, 30]}" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = Foo()\n", "vars(f)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 100, 'y': [10, 20, 30]}" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g = Foo()\n", "vars(g)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.x" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 200, 'y': [10, 20, 30]}" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.x = 200\n", "vars(f)" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 200, 'y': [10, 20, 30, 40]}" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.y.append(40)\n", "vars(f)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ " class Foo(object):\n", " def __init__(self, x, y):\n", " self.x = x\n", " self.y = y " ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "f = Foo(10, 20)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 10, 'y': 20}" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vars(f)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "__init__() missing 2 required positional arguments: 'x' and 'y'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: __init__() missing 2 required positional arguments: 'x' and 'y'" ] } ], "source": [ "f = Foo() " ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "__init__() missing 1 required positional argument: 'y'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: __init__() missing 1 required positional argument: 'y'" ] } ], "source": [ "f = Foo(10)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ " class Foo(object):\n", " def __init__(self, x=888, y=999):\n", " self.x = x\n", " self.y = y " ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 888, 'y': 999}" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = Foo()\n", "vars(f)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "class Foo(object):\n", " def __init__(self, x, *args):\n", " self.x = x\n", " self.args = args" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 10, 'args': (20, 30, 40, 50)}" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = Foo(10, 20, 30, 40, 50)\n", "vars(f)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "computers = [{'brand':'Apple', 'year':2014},\n", " {'brand':'HP', 'year':2016},\n", " {'brand':'Lenovo', 'year':2016},\n", " {'brand':'Apple', 'year':2010} ]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Apple, from 2014\n", "HP, from 2016\n", "Lenovo, from 2016\n", "Apple, from 2010\n" ] } ], "source": [ "for one_computer in computers:\n", " print(f\"{one_computer['brand']}, from {one_computer['year']}\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HP, from 2016\n", "Lenovo, from 2016\n" ] } ], "source": [ "for one_computer in computers:\n", " if one_computer['year'] == 2016:\n", " print(f\"{one_computer['brand']}, from {one_computer['year']}\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "class Computer(object):\n", " def __init__(self, brand, year):\n", " self.brand = brand\n", " self.year = year\n", " \n", "c1 = Computer('Apple', 2014)\n", "c2 = Computer('HP', 2016)\n", "c3 = Computer('Lenovo', 2016)\n", "c4 = Computer('Apple', 2010)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Apple, from 2014\n", "HP, from 2016\n", "Lenovo, from 2016\n", "Apple, from 2010\n" ] } ], "source": [ "my_computers = [c1, c2, c3, c4]\n", "\n", "for one_computer in my_computers:\n", " print(f\"{one_computer.brand}, from {one_computer.year}\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter title (or to stop): title1\n", "Enter author: author1\n", "Enter price: 1111\n", "Enter title (or to stop): title2\n", "Enter author: author2\n", "Enter price: 222\n", "Enter title (or to stop): title3\n", "Enter author: author2\n", "Enter price: 333\n", "Enter title (or to stop): \n", "[<__main__.Book object at 0x102816908>, <__main__.Book object at 0x1028167f0>, <__main__.Book object at 0x102816a20>]\n" ] } ], "source": [ "class Book(object):\n", " def __init__(self, title, author, price):\n", " self.title = title\n", " self.author = author\n", " self.price = price\n", " \n", "all_books = [ ]\n", "while True:\n", " title = input(\"Enter title (or to stop): \").strip()\n", " if not title:\n", " break\n", " author = input(\"Enter author: \").strip()\n", " price = float(input(\"Enter price: \"))\n", " \n", " all_books.append(Book(title, author, price))\n", " \n", "print(all_books)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "chocolate\n", "chocolate\n", "vanilla\n", "coffee\n" ] } ], "source": [ "# (1) Scoop class -- each instance is one scoop of ice cream\n", "\n", "class Scoop(object):\n", " def __init__(self, flavor):\n", " self.flavor = flavor\n", "\n", "\n", "s1 = Scoop('chocolate')\n", "s2 = Scoop('vanilla')\n", "s3 = Scoop('coffee')\n", "\n", "print(s1.flavor) # chocolate\n", "\n", "for one_scoop in [s1, s2, s3]:\n", " print(one_scoop.flavor) # chocolate, vanilla, coffee\n", "\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# (2) Person class -- name, e-mail address, and phone number\n", "\n", "# Create several people, and iterate over them in a list\n", "# and print their names (similar to a phone book)\n", "\n", "# Change the e-mail address of one person, and show\n", "# that it has changed by printing your list a second time\n", "\n", "class Person(object):\n", " def __init__(self, name, email, phone):\n", " self.name = name\n", " self.email = email\n", " self.phone = phone\n", " \n", "p1 = Person('Reuven', 'reuven@lerner.co.il', '123456')\n", "p2 = Person('Joe Schmoe', 'joe@schmoe.com', '555666777')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Reuven\n" ] } ], "source": [ "print(p1.name)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "reuven@lerner.co.il\n" ] } ], "source": [ "print(p1.email)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "123456\n" ] } ], "source": [ "print(p1.phone)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Reuven, phone 123456, email reuven@lerner.co.il\n", "Joe Schmoe, phone 555666777, email joe@schmoe.com\n" ] } ], "source": [ "phone_book = [p1, p2]\n", "\n", "for one_person in phone_book:\n", " print(f\"{one_person.name}, phone {one_person.phone}, email {one_person.email}\")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "p2.phone = 99999" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.Person at 0x102816550>" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p2" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "99999" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p2.phone" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Reuven, phone 123456, email reuven@lerner.co.il\n", "Joe Schmoe, phone 99999, email joe@schmoe.com\n" ] } ], "source": [ "for one_person in phone_book:\n", " print(f\"{one_person.name}, phone {one_person.phone}, email {one_person.email}\")" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# (3) Create a BankAccount class. It'll have a single\n", "# attribute (per instance), transactions -- a list of floats\n", "\n", "# Every time you deposit, append a positive float\n", "# Every time you withdraw, append a negative float\n", "\n", "# (a) create two different accounts\n", "# (b) add a number of transactions +/- to each account\n", "# (c) show, for each account, the number of transactions\n", "# and the average amount per transaction, as well as\n", "# the current balance. (assume it starts at 0)\n", "\n", "\n", "class BankAccount(object):\n", " def __init__(self):\n", " self.transactions = [ ]\n", " \n", "checking = BankAccount()\n", "savings = BankAccount()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "checking.transactions.append(100)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "checking.transactions.append(-50)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "checking.transactions.append(500)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "checking.transactions.append(-250)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "300" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(checking.transactions)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "75.0" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(checking.transactions) / len(checking.transactions)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(savings.transactions)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "savings.transactions.append(1000)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "savings.transactions.append(2000)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "savings.transactions.append(-100)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2900" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(savings.transactions)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "966.6666666666666" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(savings.transactions) / len(savings.transactions)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def x2(self):\n", " return self.x * 2" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "f = Foo(10)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'x': 10}" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vars(f)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.x2() # invokes the method x2 on our f object" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Foo.x2(f) # the above line, f.x2(), is secretly rewritten to look like this!" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def x2(self):\n", " return self.x * 2" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mx2\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mx2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "source": [ "f = Foo(10)\n", "f.x2()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "20\n" ] } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def get_x(self):\n", " return self.x\n", " \n", " def set_x(self, new_x):\n", " self.x = new_x\n", " \n", "f = Foo(10)\n", "print(f.get_x())\n", "f.set_x(20)\n", "print(f.get_x())" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "20\n" ] } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", "# def get_x(self): # getter or accessor\n", "# return self.x\n", " \n", "# def set_x(self, new_x): # setter or mutator \n", "# self.x = new_x\n", " \n", "f = Foo(10)\n", "print(f.x)\n", "f.x = 20\n", "print(f.x)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "class Book(object):\n", " def __init__(self, title, author, price=30):\n", " self.title = title\n", " self.author = author\n", " self.price = price\n", " \n", " def nice_author_name(self):\n", " return ', '.join(reversed(self.author.split()))\n", " \n", " def price_with_tax(self):\n", " return self.price * 1.15\n", " \n", "b1 = Book('Title1', 'John Smith')\n", "b2 = Book('Title2', 'David Cohen')\n", "b3 = Book('TItle3', 'David Cohen', 25)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1.price" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b2.price" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b3.price" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'John Smith'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1.author" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'David Cohen'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b2.author" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Smith, John'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1.nice_author_name()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Cohen, David'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b2.nice_author_name()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "34.5" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1.price_with_tax()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "34.5" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b2.price_with_tax()\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "28.749999999999996" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b3.price_with_tax()" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# has-a relationship -- composition\n", "# Bookshelf has-a book\n", "\n", "class Bookshelf(object):\n", " def __init__(self):\n", " self.books = [ ]\n", " \n", " def add_books(self, *args):\n", " self.books += args\n", " \n", " def total_price(self):\n", " return sum([one_book.price\n", " for one_book in shelf.books]) \n", " \n", "shelf = Bookshelf()\n", "shelf.add_books(b1, b2)\n", "shelf.add_books(b3)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[<__main__.Book at 0x10f6f1828>,\n", " <__main__.Book at 0x10f6f1780>,\n", " <__main__.Book at 0x10f6f1198>]" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "shelf.books" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Title1'" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "shelf.books[0].title" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "85" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "shelf.total_price()" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'chocolate, vanilla, coffee'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (1) Create a Bowl class. We can put scoops in the bowl!\n", "\n", "class Scoop(object):\n", " def __init__(self, flavor):\n", " self.flavor = flavor\n", " \n", "s1 = Scoop('chocolate')\n", "s2 = Scoop('vanilla')\n", "s3 = Scoop('coffee')\n", "\n", "class Bowl(object):\n", " def __init__(self):\n", " self.scoops = [ ]\n", " \n", " def add_scoops(self, *new_scoops):\n", " self.scoops += new_scoops\n", " \n", " def flavors(self):\n", " return ', '.join([one_scoop.flavor\n", " for one_scoop in self.scoops])\n", "\n", "b = Bowl()\n", "b.add_scoops(s1, s2)\n", "b.add_scoops(s3)\n", "b.flavors() # returns a string of \"chocolate, vanilla, coffee\"\n" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[<__main__.Scoop at 0x10f6fdeb8>,\n", " <__main__.Scoop at 0x10f6fde48>,\n", " <__main__.Scoop at 0x10f6fde80>]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.scoops" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[<__main__.BankAccount object at 0x10f799518>, <__main__.BankAccount object at 0x10f77f048>]\n" ] } ], "source": [ "class Person(object):\n", " def __init__(self, name):\n", " self.name = name\n", " self.accounts = [ ]\n", " \n", " def add_account(self, new_account):\n", " self.accounts.append(new_account)\n", " \n", " def all_balances(self):\n", " return [sum(one_account.transactions)\n", " for one_account in self.accounts]\n", " \n", " def current_total_balance(self):\n", " return sum([sum(one_account.transactions)\n", " for one_account in self.accounts])\n", " \n", " def average_transaction_amount(self):\n", " all_transactions = [one_transaction\n", " for one_account in self.accounts\n", " for one_transaction in one_account.transactions]\n", " \n", " print(all_transactions)\n", " \n", " return sum(all_transactions) / len(all_transactions)\n", "\n", "\n", "\n", "class BankAccount(object):\n", " def __init__(self):\n", " self.transactions = [ ]\n", " \n", "# (2) Use our existing Person and BankAccount classes. Make it possible\n", "# for a person to have one or more bank accounts. So we can say:\n", "\n", "p1 = Person('Person1')\n", "\n", "ba1 = BankAccount()\n", "ba1.transactions.append(100)\n", "ba1.transactions.append(200)\n", "ba1.transactions.append(-50)\n", "ba1.transactions.append(500)\n", "\n", "ba2 = BankAccount()\n", "ba2.transactions.append(1000)\n", "ba2.transactions.append(2000)\n", "ba2.transactions.append(-500)\n", "ba2.transactions.append(5000)\n", "\n", "p1.add_account(ba1)\n", "p1.add_account(ba2)\n", "\n", "print(p1.accounts)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[750, 7500]" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p1.all_balances() # returns a list of floats representing balances" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8250" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p1.current_total_balance() # gives the total balance across all accounts" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[100, 200, -50, 500, 1000, 2000, -500, 5000]\n" ] }, { "data": { "text/plain": [ "1031.25" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p1.average_transaction_amount() # returns the average amount of transactions across all accounts" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len([100, 200, -50, 500, 1000, 2000, -500, 5000])" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8250" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum([100, 200, -50, 500, 1000, 2000, -500, 5000])" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "46" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (3) Create a ShoppingCart class.\n", "\n", "class ShoppingCart(object):\n", " def __init__(self):\n", " self.items = { }\n", " \n", " def add(self, name, price, new_quantity):\n", " if name in self.items:\n", " price, previous_quantity = self.items[name]\n", " self.items[name] = (price, previous_quantity + new_quantity)\n", " else:\n", " self.items[name] = (price, new_quantity)\n", " \n", " def remove(self, name):\n", " if name in self.items:\n", " price, quantity = self.items[name]\n", " if quantity == 1:\n", " del(self.items[name])\n", " else:\n", " self.items[name] = (price, quantity-1)\n", " \n", " def total(self):\n", " return sum([price * quantity\n", " for price, quantity in self.items.values()])\n", " \n", "sc = ShoppingCart()\n", "sc.add('book', 30, 1) # name, price-per-unit, quantity\n", "sc.add('toothbrush', 4, 3)\n", "sc.add('toothbrush', 4, 1)\n", "\n", "\n", "sc.remove('toothbrush') # removes one toothbrush -- or removes\n", " # the item altogether if the quantity is 0\n", "\n", "sc.total() # returns the total price of items in the shopping cart\n" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'book': (30, 1), 'toothbrush': (4, 4)}" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sc.items" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A\n", "B\n", "D\n", "E\n", "['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'greet']\n", "C\n", "C\n", "Hello, name1\n", "Hello, name2\n" ] } ], "source": [ "print('A')\n", "class Person(object):\n", " print('B')\n", " def __init__(self, name):\n", " print('C') \n", " self.name = name\n", " \n", " print('D')\n", "\n", " def greet(self):\n", " return f\"Hello, {self.name}\"\n", "print('E')\n", "\n", "print(dir(Person))\n", "\n", "p1 = Person('name1')\n", "p2 = Person('name2')\n", "\n", "print(p1.greet())\n", "print(p2.greet())" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before, population = 0\n", "After, population = 0\n", "After, p1.population = 1\n", "After, p2.population = 1\n" ] } ], "source": [ "class Person(object):\n", " population = 0 # this defines Person.population = 0 -- class attribute\n", " \n", " def __init__(self, name):\n", " self.population += 1\n", " self.name = name\n", " \n", "\n", "print(f\"Before, population = {Person.population}\")\n", "p1 = Person('name1')\n", "p2 = Person('name2')\n", "print(f\"After, population = {Person.population}\")\n", "print(f\"After, p1.population = {p1.population}\")\n", "print(f\"After, p2.population = {p2.population}\")\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# If I ask for a.b:\n", "# (1) looks for \"b\" attribute on \"a\"\n", "# (2) looks for \"b\" attribute on type(a)\n", "# (3) looks for \"b\" attribute on object\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'chocolate, vanilla, coffee'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (1) Create a Bowl class. We can put scoops in the bowl!\n", "\n", "class Scoop(object):\n", " def __init__(self, flavor):\n", " self.flavor = flavor\n", " \n", "s1 = Scoop('chocolate')\n", "s2 = Scoop('vanilla')\n", "s3 = Scoop('coffee')\n", "s4 = Scoop('flavor 4')\n", "s5 = Scoop('flavor 5')\n", "s6 = Scoop('flavor 6')\n", "\n", "class Bowl(object):\n", " max_scoops = 3 # class attribute!\n", " \n", " def __init__(self):\n", " self.scoops = [ ]\n", " \n", " def add_scoops(self, *new_scoops):\n", " self.scoops += new_scoops[:Bowl.max_scoops-len(self.scoops)]\n", " \n", " def flavors(self):\n", " return ', '.join([one_scoop.flavor\n", " for one_scoop in self.scoops])\n", "\n", "b = Bowl()\n", "b.add_scoops(s1, s2)\n", "b.add_scoops(s3, s4, s5, s6)\n", "b.flavors() # returns a string of \"chocolate, vanilla, coffee\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# (1) Modify the Bowl class, such that adding a new scoop to the bowl\n", "# will only work if you have fewer than 3 scoops. In other words: max 3\n", "# scoops per bowl.\n", "\n", "# Adding a new scoop to a bowl that is already full will be silently\n", "# ignored.\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "500" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\n", "# (2) Create a Loan class. Each time someone creates a new Loan, it's\n", "# for a certain amount of money. That money is taken from the\n", "# bank's available assets.\n", "\n", "# l1 = Loan(500)\n", "# l2 = Loan(200)\n", "# l3 = Loan(700) # raises an exception -- ValueError to indicate no money\n", "# l1.repay(500)\n", "# l3 = Loan(700) # now it'll work, because the bank has sufficient funds\n", "\n", "\n", "class Loan(object):\n", " bank_assets = 1000\n", " \n", " def __init__(self, amount):\n", " if Loan.bank_assets >= amount:\n", " self.amount_owed = amount\n", " Loan.bank_assets -= amount\n", " else:\n", " raise ValueError(\"Bank doesn't have enough\")\n", " \n", " def repay(self, repayment_amount):\n", " self.amount_owed -= repayment_amount\n", " Loan.bank_assets += repayment_amount\n", " \n", "l1 = Loan(500)\n", "l1.amount_owed" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "500" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Loan.bank_assets" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "200" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l2 = Loan(200)\n", "l2.amount_owed" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "300" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Loan.bank_assets" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1.repay(500)\n", "l1.amount_owed" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "800" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Loan.bank_assets" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, name1\n", "Hello, name2\n" ] } ], "source": [ "class Person(object):\n", " def __init__(self, name):\n", " self.name = name\n", " \n", " def greet(self):\n", " return f\"Hello, {self.name}\"\n", " \n", "p1 = Person('name1')\n", "p2 = Person('name2')\n", "\n", "print(p1.greet())\n", "print(p2.greet())\n", " \n", " " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, emp1\n", "Hello, emp2\n" ] } ], "source": [ "class Employee(Person):\n", " def __init__(self, name, employee_id):\n", " super().__init__(name)\n", " self.employee_id = employee_id\n", " \n", "e1 = Employee('emp1', 1)\n", "e2 = Employee('emp2', 2)\n", "\n", "print(e1.greet())\n", "print(e2.greet())\n", " \n", "# a.b # \n", "\n", "# (1) does \"b\" exist as an attribute on a?\n", "# (2) does \"b\" exist as an attribute on a's class?\n", "# (3) does \"b\" exist as an attribute on a's parent class?\n", "# repeat this until we get to a class whose parent is \"object\"\n", "# (4) does \"b\" exist as an attribute on object?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello, name1'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (1) Take our existing Person class, and add a subclass, called\n", "# VerbosePerson. This class works the same way as Person, except that\n", "# the \"greet\" method doesn't just return \"Hello, NAME\" but rather\n", "# something longer than that.\n", "\n", "class Person(object):\n", " def __init__(self, name):\n", " self.name = name\n", " \n", " def greet(self):\n", " return f\"Hello, {self.name}\"\n", " \n", "p1 = Person('name1')\n", "p1.greet()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, name2. How are you? Have you seen pictures of my children lately? They're so lovely!\n", "You're asking me Why is the sky blue?? I can answer you at great length!\n" ] } ], "source": [ "class VerbosePerson(Person):\n", " def greet(self):\n", " return f\"Hello, {self.name}. How are you? Have you seen pictures of my children lately? They're so lovely!\"\n", " \n", " def answer_question(self, text):\n", " return f\"You're asking me {text}? I can answer you at great length!\"\n", "\n", "p2 = VerbosePerson('name2')\n", "print(p2.greet())\n", "print(p2.answer_question('Why is the sky blue?'))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "54.1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (3) Create a ShoppingCart class.\n", "\n", "class ShoppingCart(object):\n", " def __init__(self):\n", " self.items = { }\n", " \n", " def add(self, name, price, new_quantity):\n", " if name in self.items:\n", " price, previous_quantity = self.items[name]\n", " self.items[name] = (price, previous_quantity + new_quantity)\n", " else:\n", " self.items[name] = (price, new_quantity)\n", " \n", " def remove(self, name):\n", " if name in self.items:\n", " price, quantity = self.items[name]\n", " if quantity == 1:\n", " del(self.items[name])\n", " else:\n", " self.items[name] = (price, quantity-1)\n", " \n", " def total(self):\n", " return sum([price * quantity\n", " for price, quantity in self.items.values()])\n", " \n", "\n", "class OnlineShoppingCart(ShoppingCart):\n", " def total(self):\n", " return (1.05 * super().total()) + 10\n", " \n", "sc = OnlineShoppingCart()\n", "sc.add('book', 30, 1) # name, price-per-unit, quantity\n", "sc.add('toothbrush', 4, 3)\n", "sc.add('toothbrush', 4, 1)\n", "\n", "sc.remove('toothbrush') # removes one toothbrush -- or removes\n", " # the item altogether if the quantity is 0\n", "\n", "sc.total() # returns the total price of items in the shopping cart\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'chocolate, vanilla, coffee'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (1) Create a Bowl class. We can put scoops in the bowl!\n", "\n", "class Scoop(object):\n", " def __init__(self, flavor):\n", " self.flavor = flavor\n", " \n", "s1 = Scoop('chocolate')\n", "s2 = Scoop('vanilla')\n", "s3 = Scoop('coffee')\n", "s4 = Scoop('flavor 4')\n", "s5 = Scoop('flavor 5')\n", "s6 = Scoop('flavor 6')\n", "\n", "class Bowl(object):\n", " max_scoops = 3 # class attribute!\n", " \n", " def __init__(self):\n", " self.scoops = [ ]\n", " \n", " def add_scoops(self, *new_scoops):\n", " self.scoops += new_scoops[:self.max_scoops-len(self.scoops)]\n", " \n", " def flavors(self):\n", " return ', '.join([one_scoop.flavor\n", " for one_scoop in self.scoops])\n", "\n", "b = Bowl()\n", "b.add_scoops(s1, s2)\n", "b.add_scoops(s3, s4, s5, s6)\n", "b.flavors() # returns a string of \"chocolate, vanilla, coffee\"\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'chocolate, vanilla, coffee, flavor 4, flavor 5'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class BigBowl(Bowl):\n", " max_scoops = 5 # class attribute!\n", " \n", " \n", "bb = BigBowl()\n", "bb.add_scoops(s1, s2)\n", "bb.add_scoops(s3, s4, s5, s6)\n", "bb.flavors() # should give me 5 flavors, because it's a big bowl!\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Meeting at: \n", "\t2018-May-10 10:00\n", "\t2018-May-12 10:00\n" ] } ], "source": [ "class Course(object):\n", " def __init__(self, title, teacher):\n", " self.title = title\n", " self.teacher = teacher\n", " self.meetings = [ ]\n", " self.students = [ ]\n", " \n", " def add_meeting(self, new_meeting):\n", " self.meetings.append(new_meeting)\n", " \n", " def add_student(self, new_student):\n", " self.students.append(new_student)\n", " \n", " def all_meetings(self):\n", " return 'Meeting at: \\n' + '\\n'.join(['\\t' + one_meeting\n", " for one_meeting in self.meetings])\n", " \n", "c1 = Course('Python', 'Reuven')\n", "c1.add_meeting('2018-May-10 10:00')\n", "c1.add_meeting('2018-May-12 10:00')\n", "\n", "c1.add_student('Joe')\n", "c1.add_student('Mary')\n", "\n", "\n", "print(c1.all_meetings())\n", " \n", " \n", " \n", " " ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Joe': 'joe', 'Mary': 'mary'}\n" ] } ], "source": [ "class OnlineCourse(Course):\n", " def __init__(self, title, teacher, url):\n", " super().__init__(title, teacher)\n", " self.url = url\n", " \n", " def get_username(self, student):\n", " return student.lower()\n", " \n", " def all_usernames(self):\n", " return {one_student : self.get_username(one_student)\n", " for one_student in self.students}\n", " \n", "c2 = OnlineCourse('Online Python', 'Reuven', 'http://lerner.co.il/')\n", "c2.add_meeting('2018-May-10 10:00')\n", "c2.add_meeting('2018-May-12 10:00')\n", "\n", "c2.add_student('Joe')\n", "c2.add_student('Mary')\n", "\n", "print(c2.all_usernames())" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Course,)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# OnlineCourse is-a Course : OnlineCourse inherits from Course\n", "\n", "OnlineCourse.__bases__ " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Meeting at: \n", "\t2018-May-10 10:00\n", "\t2018-May-12 10:00\n" ] } ], "source": [ "print(c2.all_meetings()) " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(object,)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Course.__bases__" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "()" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "object.__bases__" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'abcd'\n", "len(s)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [10, 20, 30]\n", "len(mylist)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {'a':1, 'b':2, 'c':3}\n", "len(d)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "object of type 'Foo' has no len()", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'abcd'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: object of type 'Foo' has no len()" ] } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", "f = Foo('abcd')\n", "len(f)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# magic method __whatever__ \n", "\n", "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return len(self.x)\n", " \n", "f = Foo('abcd')\n", "len(f)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.__len__()" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'float' object cannot be interpreted as an integer", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mFoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'abcd'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'float' object cannot be interpreted as an integer" ] } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return 1.5\n", " \n", "f = Foo('abcd')\n", "len(f)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return len(self.x)\n", " \n", "f = Foo('abcd')\n", "len(f)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.Foo object at 0x10517e390>\n" ] } ], "source": [ "print(f)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'<__main__.Foo object at 0x10517e390>'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(f) " ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "# __str__" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm a Foo, with vars = {'x': 'abcd'}\n" ] } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return len(self.x)\n", " \n", " def __str__(self):\n", " return f\"I'm a Foo, with vars = {vars(self)}\"\n", " \n", "f = Foo('abcd')\n", "print(f) # str(f) -> f.__str__() " ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"f = I'm a Foo, with vars = {'x': 'abcd'}\"" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f\"f = {f}\" " ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.Foo at 0x10517eba8>" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# __str__ -- the string version of an object, for common usage\n", "# __repr__ -- the string version of an object, for developers\n", "\n", "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return len(self.x)\n", " \n", " def __str__(self):\n", " return f\"[str] I'm a Foo, with vars = {vars(self)}\"\n", " \n", " def __repr__(self):\n", " return f\"[repr] I'm a Foo, with vars = {vars(self)}\"\n", "\n", "f = Foo('abcd')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[str] I'm a Foo, with vars = {'x': 'abcd'}\n" ] } ], "source": [ "print(f)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"[str] I'm a Foo, with vars = {'x': 'abcd'}\"" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(f)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"f = [str] I'm a Foo, with vars = {'x': 'abcd'}\"" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f\"f = {f}\"" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[repr] I'm a Foo, with vars = {'x': 'abcd'}]" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [f]\n", "mylist" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[repr] I'm a Foo, with vars = {'x': 'abcd'}" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "# __str__ -- the string version of an object, for common usage\n", "# __repr__ -- the string version of an object, for developers\n", "\n", "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __len__(self):\n", " return len(self.x)\n", " \n", " def __repr__(self):\n", " return f\"[repr] I'm a Foo, with vars = {vars(self)}\"\n", "\n", "f = Foo('abcd')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[repr] I'm a Foo, with vars = {'x': 'abcd'}\n" ] } ], "source": [ "print(f)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"[repr] I'm a Foo, with vars = {'x': 'abcd'}\"" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(f)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"f = [repr] I'm a Foo, with vars = {'x': 'abcd'}\"" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f\"f = {f}\"" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'chocolate, vanilla, coffee, flavor 4, flavor 5'" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (1) Make it possible to run len() on our Bowl/BigBowl objects. This\n", "# will report the number of scoops in a bowl.\n", "\n", "# b = Bowl()\n", "# b.add_scoops(s1, s2, s3)\n", "# len(b) # return 3\n", "\n", "# (1) Create a Bowl class. We can put scoops in the bowl!\n", "\n", "class Scoop(object):\n", " def __init__(self, flavor):\n", " self.flavor = flavor\n", " \n", " def __repr__(self):\n", " return f\"Scoop of {self.flavor}\"\n", " \n", "s1 = Scoop('chocolate')\n", "s2 = Scoop('vanilla')\n", "s3 = Scoop('coffee')\n", "s4 = Scoop('flavor 4')\n", "s5 = Scoop('flavor 5')\n", "s6 = Scoop('flavor 6')\n", "\n", "class Bowl(object):\n", " max_scoops = 3 # class attribute!\n", " \n", " def __init__(self):\n", " self.scoops = [ ]\n", " \n", " def add_scoops(self, *new_scoops):\n", " self.scoops += new_scoops[:self.max_scoops-len(self.scoops)]\n", " \n", " def flavors(self):\n", " return ', '.join([one_scoop.flavor\n", " for one_scoop in self.scoops])\n", " \n", " def __len__(self):\n", " return len(self.scoops)\n", " \n", " def __repr__(self):\n", " output = 'Bowl with: \\n'\n", " output += '\\n'.join([f\"\\t{index} {one_scoop}\"\n", " for index, one_scoop in enumerate(self.scoops, 1)])\n", " return output\n", "\n", "b = Bowl()\n", "b.add_scoops(s1, s2)\n", "b.add_scoops(s3, s4, s5, s6)\n", "b.flavors() # returns a string of \"chocolate, vanilla, coffee\"\n", "\n", "class BigBowl(Bowl):\n", " max_scoops = 5 # class attribute!\n", " \n", " \n", "bb = BigBowl()\n", "bb.add_scoops(s1, s2)\n", "bb.add_scoops(s3, s4, s5, s6)\n", "bb.flavors() # should give me 5 flavors, because it's a big bowl!\n" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bowl with: \n", "\t1 Scoop of chocolate\n", "\t2 Scoop of vanilla\n", "\t3 Scoop of coffee\n" ] } ], "source": [ "print(b)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bowl with: \n", "\t1 Scoop of chocolate\n", "\t2 Scoop of vanilla\n", "\t3 Scoop of coffee\n", "\t4 Scoop of flavor 4\n", "\t5 Scoop of flavor 5\n" ] } ], "source": [ "print(bb)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(b)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(bb) # bb.__len__ " ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Scoop of chocolate\n" ] } ], "source": [ "# (2) Make it possible to \"print\" our Scoop and Bowl. If I say\n", "\n", "# print(s1)\n", "\n", "# it'll print\n", "\n", "# Scoop of chocolate\n", "\n", "# mylist = [s1, s2, s3]\n", "\n", "# print(mylist)\n", "\n", "# [Scoop of chocolate, Scoop of vanilla, Scoop of coffee]\n", "\n", "# print(b)\n", "\n", "# Bowl with:\n", "# \t1) Scoop of chocolate\n", "# \t2) Scoop of vanilla\n", "# \t2) Scoop of coffee\n", "\n", "print(s1)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Scoop of chocolate, Scoop of vanilla, Scoop of coffee]\n" ] } ], "source": [ "print(b.scoops)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.Bowl object at 0x105182f98>\n" ] } ], "source": [ "print(b)" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# (3) Make len() and print() work on the Shopping Cart. If I say\n", "# len(sc), it'll return the number of items in the cart.\n", "\n", "# print(sc)\n", "\n", "# It'll show each item in the cart -- name, per-unit price,\n", "# quantity, and total price for that item. *PLUS* it'll show the\n", "# total price of all items\n", "\n", "# item1 2 $1 $2\n", "# item2 6 $3 $18\n", "# -----------------------\n", "# Total $20\n", " \n", "\n", "# (3) Create a ShoppingCart class.\n", "\n", "class ShoppingCart(object):\n", " def __init__(self):\n", " self.items = { }\n", " \n", " def add(self, name, price, new_quantity):\n", " if name in self.items:\n", " price, previous_quantity = self.items[name]\n", " self.items[name] = (price, previous_quantity + new_quantity)\n", " else:\n", " self.items[name] = (price, new_quantity)\n", " \n", " def remove(self, name):\n", " if name in self.items:\n", " price, quantity = self.items[name]\n", " if quantity == 1:\n", " del(self.items[name])\n", " else:\n", " self.items[name] = (price, quantity-1)\n", " \n", " def total(self):\n", " return sum([price * quantity\n", " for price, quantity in self.items.values()])\n", " \n", " def __len__(self):\n", " return sum([quantity\n", " for price, quantity in self.items.values()])\n", " \n", " def __repr__(self):\n", " output = [ ]\n", " for name, info in self.items.items():\n", " price, quantity = info\n", " output.append(f\"{name:10} {quantity:3} ${price:3} ${quantity*price:4}\")\n", " output.append(f\"Total: {self.total():20}\")\n", " return '\\n'.join(output)\n", " \n", "sc = ShoppingCart()\n", "sc.add('book', 30, 1) # name, price-per-unit, quantity\n", "sc.add('toothbrush', 4, 3)\n", "sc.add('toothbrush', 4, 1)\n", "\n", "\n", "sc.remove('toothbrush') # removes one toothbrush -- or removes\n", " # the item altogether if the quantity is 0\n", "\n", "sc.total() # returns the total price of items in the shopping cart\n" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(sc)" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "book 1 $ 30 $ 30\n", "toothbrush 3 $ 4 $ 12\n", "Total: 42\n" ] } ], "source": [ "print(sc)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 2" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int.__add__(2,2)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abcdef'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str.__add__('abc', 'def')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello, Reuven'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name = 'Reuven'\n", "'Hello, %s' % name" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello, Reuven'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Hello, %s'.__mod__(name)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abcde'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Foo(object):\n", " def __init__(self, x):\n", " self.x = x\n", " \n", " def __getitem__(self, index):\n", " return self.x[index]\n", "\n", "f = Foo('abcde')\n", "f.x" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'d'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f[3] # f.__getitem__(3) .... f.x[3]" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'int' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'int' object is not subscriptable" ] } ], "source": [ "x =5\n", "x[3]" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "black Wolf, 4 legs\n", "white Sheep, 4 legs\n", "white Sheep, 4 legs\n", "brown Snake, 0 legs\n", "black Parrot, 2 legs\n", "Cage 1\n", "\t1 black Wolf, 4 legs\n", "\t2 white Sheep, 4 legs\n", "\t3 white Sheep, 4 legs\n", "Cage 2\n", "\t1 brown Snake, 0 legs\n", "\t2 black Parrot, 2 legs\n", "Cage 1\n", "\t1 black Wolf, 4 legs\n", "\t2 white Sheep, 4 legs\n", "\t3 white Sheep, 4 legs\n", "Cage 2\n", "\t1 brown Snake, 0 legs\n", "\t2 black Parrot, 2 legs\n", "black Wolf, 4 legs\n", "black Parrot, 2 legs\n", "14\n" ] } ], "source": [ "class Animal(object):\n", " def __init__(self, color):\n", " self.color = color\n", " self.species = self.__class__.__name__\n", " def __repr__(self):\n", " return f\"{self.color} {self.species}, {self.number_of_legs} legs\"\n", "\n", "class Wolf(Animal):\n", " def __init__(self, color):\n", " super().__init__(color)\n", " self.number_of_legs = 4\n", " \n", "class Sheep(Animal):\n", " def __init__(self, color):\n", " super().__init__(color)\n", " self.number_of_legs = 4\n", "\n", "class Snake(Animal):\n", " def __init__(self, color):\n", " super().__init__(color)\n", " self.number_of_legs = 0\n", "\n", "class Parrot(Animal):\n", " def __init__(self, color):\n", " super().__init__(color)\n", " self.number_of_legs = 2\n", " \n", "wolf = Wolf('black') # species, color, # legs\n", "sheep1 = Sheep('white')\n", "sheep2 = Sheep('white') \n", "snake = Snake('brown')\n", "parrot = Parrot('black')\n", "\n", "print(wolf) # black wolf, 4 legs # str(wolf) -> wolf.__str__ \n", "print(sheep1) # white sheep, 4 legs\n", "print(sheep2) # white sheep, 4 legs\n", "print(snake) # brown snake, 0 legs\n", "print(parrot) # black parrot, 2 legs\n", "\n", "class Cage(object):\n", " def __init__(self, id_number):\n", " self.id_number = id_number\n", " self.animals = [ ]\n", " def add_animals(self, *new_animals):\n", " self.animals += new_animals\n", " def __repr__(self):\n", " output = f'Cage {self.id_number}\\n'\n", " output += '\\n'.join([f'\\t{index} {one_animal}'\n", " for index, one_animal in enumerate(self.animals, 1)]) \n", " return output\n", " def animals_by_color(self, color):\n", " return '\\n'.join([str(one_animal)\n", " for one_animal in self.animals\n", " if one_animal.color == color])\n", "\n", "c1 = Cage(1) # ID numbers\n", "c1.add_animals(wolf, sheep1, sheep2)\n", "print(c1)\n", "\n", "c2 = Cage(2)\n", "c2.add_animals(snake, parrot)\n", "print(c2)\n", "\n", "class Zoo(object):\n", " def __init__(self):\n", " self.cages = [ ]\n", " def add_cages(self, *new_cages):\n", " self.cages += new_cages\n", " def __repr__(self):\n", " return '\\n'.join([str(one_cage)\n", " for one_cage in self.cages])\n", " def animals_by_color(self, color):\n", " return '\\n'.join([one_cage.animals_by_color(color)\n", " for one_cage in self.cages]) \n", " \n", " def animals_by_color2(self, color):\n", " return '\\n'.join([str(one_animal)\n", " for one_cage in self.cages\n", " for one_animal in one_cage.animals\n", " if one_animal.color == color])\n", " \n", " def number_of_legs(self):\n", " return sum([one_animal.number_of_legs\n", " for one_cage in self.cages\n", " for one_animal in one_cage.animals])\n", " \n", " \n", "\n", "z = Zoo()\n", "z.add_cages(c1, c2)\n", "print(z)\n", "\n", "print(z.animals_by_color2('black')) \n", "print(z.number_of_legs())\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }