###################################################### # CptS 111, Fall 2012 # Lecture 06 # 1/30/2012 # John B. Schneider # Diary of in-class presentation. ###################################################### Python 3.2.2 (v3.2.2:137e45f15c0b, Sep 3 2011, 17:28:59) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ################################################### ... # Started class with a demonstration and discussion of the ... # solution to each of the homework problems. ... # ... ################################################### ... # Last time we started talking about objects. ... # ... # Recall that an object is a collection of attributes (data) and ... # methods (functions). ... # ... # The attributes and methods for all the objects in a given ... # class are determined by a class statement. The class statement ... # forms a kind of blueprint for the objects in general. ... # ... # From last time... ... >>> class Patient: ... name = "Jane Doe" # Default name. ... age = 0 # Default age. ... malady = "healthy" # Default malady. ... >>> gaga = Patient() # This creates an instance of a Patient. >>> gaga.name # Check name. 'Jane Doe' >>> gaga . name # Can have spaces around "dot." 'Jane Doe' >>> # In this context a dot (.) is known as the "access operator". It ... # "accesses" the attribute or method to the right of the dot ... # for the object to the left of the dot. ... >>> gaga.name = "Lady Gaga" # Reset name. >>> gaga.age = 25 # Reset age. >>> gaga.malady = "swollen head" # Reset malady. >>> >>> # Use a print() statement to display attributes: ... >>> print(gaga.name, gaga.age, gaga.malady, sep="; ") Lady Gaga; 25; swollen head >>> >>> # We can write a function that will help simplify the display of ... # the attributes of a Patient. Note that we can pass an object as ... # the parameter to a function. The following demonstrates this... ... >>> def show(patient): ... print(patient.name, patient.age, patient.malady, sep="; ") ... >>> show(gaga) Lady Gaga; 25; swollen head >>> >>> # Let's create a new object and show its attributes. ... >>> madonna = Patient() >>> show(madonna) Jane Doe; 0; healthy >>> >>> # Note that the show() function only makes sense for Patients. ... # ... # We can move the function into the class statement so ... # that only objects of the class can use the function. ... # When we do this, we call the function a method. But, everything ... # we've learned about creating a function still holds true. ... # ... # Let's create a new Patient class with a method to display the ... # attributes. ... >>> class Patient: ... name = "Jane Doe" ... age = 0 ... malady = "healthy" ... ... def display(self): ... print(self.name, self.age, self.malady, sep="; ") ... >>> madonna = Patient() >>> >>> # Essentially, Python converts the following statement to ... # "display(madonna)". THIS IS HOW WE ACCESS THE METHODS OF AN ... # OBJECT. Note that we don't explicitly supply the object itself ... # as an argument -- Python does that for us. ... >>> madonna.display() Jane Doe; 0; healthy >>> >>> # Reset two of madonna's attributes. ... >>> madonna.name = "Madonna" >>> madonna.age = 53 >>> # Use the display() method to see madonna's attributes. ... >>> madonna.display() Madonna; 53; healthy >>> >>> ################################################### ... # We can see a list of an object's methods and attributes ... # using the dir() function. The following shows what we get for ... # the Patient madonna. Note that the last four items in this list ... # are things we recognize, but all the rest is rather mysterious! ... # These other things are provided by Python. ... >>> dir(madonna) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'display', 'malady', 'name'] >>> # Note that in this list there is no obvious way to tell that ... # 'display' is a method while 'age' is an int. Using the type() ... # function we can display the types. ... >>> type(madonna.display) >>> type(madonna.age) >>> >>> # In Python, everything is an object. So, let's explore this a ... # bit further using a string. ... >>> s = "time to try typing" # Create a string. >>> print(s) time to try typing >>> # Use dir() to check out the string's methods/attributes. There ... # are a lot of them! ... >>> dir(s) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> # Let's try using some of these methods. >>> s.upper() # Return a copy of string in uppercase. 'TIME TO TRY TYPING' >>> s # The original string is unchanged. 'time to try typing' >>> s.title() # Obtain "title-case" for the string. 'Time To Try Typing' >>> # We can often use the help() function to obtain information about ... # a method. Let's see what we obtain for replace(). ... >>> help(s.replace) Help on built-in function replace: replace(...) S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. >>> >>> s # Reminder of what the original string is. 'time to try typing' >>> s.replace('t', 'd') # Replace t's with d's. 'dime do dry dyping' >>> s.replace('t', 'd---D') # Replace t's with something odd. 'd---Dime d---Do d---Dry d---Dyping' >>> >>> ################################################### ... # Let's again see what dir() says about our Patients. ... >>> dir(madonna) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'display', 'malady', 'name'] >>> >>> # Note the method __init__() (which leads and ends with two ... underscores). ... # Provide it exists, Python will call the __init__() method when ... # an object is created. It will pass all the parameters that ... # appeared in the class statement that created the object to the ... # __init__() method. An example helps illustrates this, so let's ... # implement yet another Patient class, but in this one we will use ... # the __init__() method and initialize attributes via its ... # parameters. ... >>> class Patient: ... # Initialization method called when object is created. ... def __init__(self, name, age, malady): ... self.name = name ... self.age = age ... self.malady = malady ... ... def display(self): ... print(self.name, self.age, self.malady, sep="; ") ... ... def cure(self): ... self.malady = "healthy" ... >>> # Create another madonna, but initialize all the attributes via ... # the parameters. ... >>> madonna = Patient("Madonna", 53, "yellow belly") >>> madonna.display() Madonna; 53; yellow belly >>> madonna.cure() >>> madonna.display() Madonna; 53; healthy >>> ################################################### ... # Operator overloading. ... # ... # Symbols can mean different things depending on the operands. ... >>> 5 + 6 # Integer addition when operands are ints. 11 >>> 5.0 + 6.0 # float addition when the operands are floats. 11.0 >>> "hello" + 5 # Cannot add string and an int. Traceback (most recent call last): File "", line 1, in TypeError: Can't convert 'int' object to str implicitly >>> # Python is aware of the operands and will do "the right thing" ... # for different combinations of operands. ... # ... # Can we add to strings? Give it a try... ... >>> "hello" + " there" 'hello there' >>> # It worked! When the operands are strings, the plus sign means ... # concatenation. ... # ... # We know we can multiple two integers. ... >>> 5 * 6 30 >>> # Can we "multiply" a string and an integer? Give it a try... >>> "hello" * 5 'hellohellohellohellohello' >>> # It worked! But, of course, this isn't really multiplication. ... # Instead, when the operands are a string and an integer, an ... # asterisk means repetition. So, in this case the result was the ... # string 'hello' repeated five times. ... # ... # Can we "multiply" a string and a float? The following shows the ... # answer is no. ... >>> "hello" * 5.0 Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'float' >>>