Please send questions to
st10@humboldt.edu .
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "copyright", "credits" or "license()" for more information.
IDLE 1.2
>>>
>>> # recall: Python definitely has objects!
>>> #
>>> # object: data + methods for acting on that
>>> # data
>>> #
>>> # and: we've been using Python objects
>>> # frequently ---
>>> # strings are objects - consider string methods such as upper
>>> food = 'spam'
>>> type(food)
<type 'str'>
>>> # call the string object food's upper method
>>> food.upper()
'SPAM'
>>> # Python calls the data fields and methods of an object
>>> # its attributes
>>>
>>> # want to see all of a object's attributes?
>>> # ...use the dir built-in function
>>>
>>> # to see the attributes of the integer
>>> # object 3
>>> dir(3)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>>> dir([1, 2, 3])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> # (setting up to import local modules...)
>>> import sys
>>> sys.path.append("/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect09")
>>> # consider lect09_1.py (posted along with this session)
>>> import lect09_1
>>> dir(lect09_1)
['__builtins__', '__doc__', '__file__', '__name__', 'spam', 'square']
>>> # what about all those odd names that begin
>>> # and end with two underscores?
>>> # ...those are SYSTEM-DEFINED NAMES
>>> # defined by the interpreter and its
>>> # implementation (including the standard
>>> # library)
>>> # "Learning Python", Section 2.3.2:
>>> # "applications should not expect to
>>> # define additional names using this
>>> # convention"
>>> dir(lect09_1)
['__builtins__', '__doc__', '__file__', '__name__', 'spam', 'square']
>>> lect09_1.__builtins__
{'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2006 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'NameError': <type 'exceptions.NameError'>, 'dict': <type 'dict'>, 'input': <built-in function input>, 'oct': <built-in function oct>, 'SystemExit': <type 'exceptions.SystemExit'>, 'StandardError': <type 'exceptions.StandardError'>, 'repr': <built-in function repr>, 'sorted': <built-in function sorted>, 'False': False, 'RuntimeWarning': <type 'exceptions.RuntimeWarning'>, 'list': <type 'list'>, 'iter': <built-in function iter>, 'reload': <built-in function reload>, 'Warning': <type 'exceptions.Warning'>, 'round': <built-in function round>, 'dir': <built-in function dir>, 'cmp': <built-in function cmp>, 'set': <type 'set'>, 'reduce': <built-in function reduce>, 'intern': <built-in function intern>, 'issubclass': <built-in function issubclass>, 'Ellipsis': Ellipsis, 'EOFError': <type 'exceptions.EOFError'>, 'locals': <built-in function locals>, 'slice': <type 'slice'>, 'FloatingPointError': <type 'exceptions.FloatingPointError'>, 'sum': <built-in function sum>, 'getattr': <built-in function getattr>, 'abs': <built-in function abs>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'True': True, 'FutureWarning': <type 'exceptions.FutureWarning'>, 'ImportWarning': <type 'exceptions.ImportWarning'>, 'None': None, 'hash': <built-in function hash>, 'len': <built-in function len>, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information., 'frozenset': <type 'frozenset'>, '__name__': '__builtin__', 'ord': <built-in function ord>, 'super': <type 'super'>, '_': None, 'TypeError': <type 'exceptions.TypeError'>, 'license': Type license() to see the full license text, 'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>, 'UserWarning': <type 'exceptions.UserWarning'>, 'filter': <built-in function filter>, 'range': <built-in function range>, 'staticmethod': <type 'staticmethod'>, 'SystemError': <type 'exceptions.SystemError'>, 'BaseException': <type 'exceptions.BaseException'>, 'pow': <built-in function pow>, 'RuntimeError': <type 'exceptions.RuntimeError'>, 'float': <type 'float'>, 'MemoryError': <type 'exceptions.MemoryError'>, 'StopIteration': <type 'exceptions.StopIteration'>, 'globals': <built-in function globals>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'apply': <built-in function apply>, 'LookupError': <type 'exceptions.LookupError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'basestring': <type 'basestring'>, 'UnicodeError': <type 'exceptions.UnicodeError'>, 'zip': <built-in function zip>, 'hex': <built-in function hex>, 'long': <type 'long'>, 'ReferenceError': <type 'exceptions.ReferenceError'>, 'ImportError': <type 'exceptions.ImportError'>, 'chr': <built-in function chr>, 'xrange': <type 'xrange'>, 'type': <type 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'Exception': <type 'exceptions.Exception'>, 'tuple': <type 'tuple'>, 'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>, 'reversed': <type 'reversed'>, 'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>, 'IOError': <type 'exceptions.IOError'>, 'hasattr': <built-in function hasattr>, 'delattr': <built-in function delattr>, 'setattr': <built-in function setattr>, 'raw_input': <built-in function raw_input>, 'SyntaxWarning': <type 'exceptions.SyntaxWarning'>, 'compile': <built-in function compile>, 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'str': <type 'str'>, 'property': <type 'property'>, 'GeneratorExit': <type 'exceptions.GeneratorExit'>, 'int': <type 'int'>, '__import__': <built-in function __import__>, 'KeyError': <type 'exceptions.KeyError'>, 'coerce': <built-in function coerce>, 'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>, 'file': <type 'file'>, 'EnvironmentError': <type 'exceptions.EnvironmentError'>, 'unichr': <built-in function unichr>, 'any': <built-in function any>, 'OSError': <type 'exceptions.OSError'>, 'DeprecationWarning': <type 'exceptions.DeprecationWarning'>, 'min': <built-in function min>, 'UnicodeWarning': <type 'exceptions.UnicodeWarning'>, 'execfile': <built-in function execfile>, 'id': <built-in function id>, 'complex': <type 'complex'>, 'bool': <type 'bool'>, 'ValueError': <type 'exceptions.ValueError'>, 'NotImplemented': NotImplemented, 'map': <built-in function map>, 'buffer': <type 'buffer'>, 'max': <built-in function max>, 'object': <type 'object'>, 'TabError': <type 'exceptions.TabError'>, 'callable': <built-in function callable>, 'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>, 'eval': <built-in function eval>, '__debug__': True, 'IndentationError': <type 'exceptions.IndentationError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 'NotImplementedError': <type 'exceptions.NotImplementedError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 'exceptions.OverflowError'>}
>>> dir(lect09_1)
['__builtins__', '__doc__', '__file__', '__name__', 'spam', 'square']
>>> # __doc__ contains the docstring, if any
>>> # for that object
>>> lect09_1.__doc__
'\nlect09_1.py - a simple module with a data attribute and a function attribute\n'
>>> lect09_1.__file__
'/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect09/lect09_1.py'
>>> lect09_1.__name__
'lect09_1'
>>> lect09_1.spam
40
>>> lect09_1.square(3)
9
>>> from lect09_1 import spam
>>> spam
40
>>> # you can "hide" stuff from the
>>> # "from module import *" statement;
>>> # IF you create a module attribute whose
>>> # name begins with a single underscore,
>>> # that name won't be copied out when
>>> # a client imports that module USING
>>> # THE FROM COMMAND
>>> # (this is to reduce some namespace
>>> # pollution - it is NOT true
>>> # data hiding!!!)
>>> # example: see lect09_2.py, posted along with this session
>>> from lect09_2 import *
>>> spam
40
>>> _spam
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
_spam
NameError: name '_spam' is not defined
>>> # BUT: all names come when you use import (rather than from):
>>> import lect09_2
>>> lect09_2.spam
40
>>> lect09_2._spam
500
>>> # one more odd "somewhat but not completely
>>> # hiding stuff" tidbit...
>>> # __all__
>>> # IF a module SETS __all__ to be a list of
>>> # some of its attribute names,
>>> # THEN the from command will ONLY copy
>>> # over THOSE names...
>>> # example: see lect09_3.py, posted along with this session
>>> from lect09_3 import *
>>> spam
4000
>>> Spam
70
>>> _spam
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
_spam
NameError: name '_spam' is not defined
>>> eggs
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
eggs
NameError: name 'eggs' is not defined
>>> sausage
Traceback (most recent call last):
File "<pyshell#92>", line 1, in <module>
sausage
NameError: name 'sausage' is not defined
>>> # again, though - all come over with import
>>> import lect09_3
>>> lect09_3.spam
4000
>>> lect09_3.Spam
70
>>> lect09_3._spam
500
>>> lect09_3.sausage
60
>>> lect09_3.eggs
50
>>> # now, a module has a __name__ attribute set for it ---
>>> # but it is a little more interesting than one may
>>> # initially guess;
>>> lect09_3.__name__
'lect09_3'
>>> lect09_2.__name__
'lect09_2'
>>> 3.__name__
SyntaxError: invalid syntax
>>> food.__name__
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
food.__name__
AttributeError: 'str' object has no attribute '__name__'
>>> # __name__ for a module is a LITTLE more
>>> # interesting than we've implied above;
>>> # ...sometimes it ISN'T the root of the
>>> # filename;
>>> # this can be used to design a module
>>> # that can be used BOTH within the
>>> # python interpreter AND at the
>>> # command line (conveniently)
>>>
>>> # Python sets __name__ as follows:
>>> # if a file is being imported,
>>> # __name__ is set to the file name
>>> # without the suffix
>>>
>>> # if a file is being run as a
>>> # "top-level" program, it is set to
>>> # the string "__main__"
>>>
>>> # SO: your module can contain code
>>> # that checks its current value
>>> # of __name__ -- and if it is "__main__"
>>> # then it can behave differently!
>>> # lect09_4.py plays with this... (and it, too, is posted along with
>>> # this session)
>>> import lect09_4
__name__ is lect09_4
>>> # for best effect, ALSO run lect09_4 from the cs-server or
>>> # redwood command line:
>>> # cs-server> python lect09_4.py
>>> #
>>> # THEN you'll see: __name__ is __main__
>>> # and lect09_5.py plays more with it...
>>> import lect09_5
>>> lect09_5.square(15)
225
>>> # BUT, if you run lect09_5 from the cs-server or redwood
>>> # command line:
>>> # cs-server> python lect09_5.py
>>> #
>>> # THEN you'll see the results of tests of lect09_5's function...
>>> # now then - a few words about
>>> # creating your own Python classes
>>> # (class: something from which you can
>>> # create new objects...)
>>> # Python classes look, let's say, different
>>> # from those you might have seen in
>>> # C++ or Java...
>>> # most classes need to define a constructor
>>> # to create new objects ---
>>> # in Python, you define a method named
>>> # __init__ to be a class constructor
>>> # (then, you "call" that constructor
>>> # by using the class name, parentheses,
>>> # and the desired constructor arguments)
>>> # self - special keyword in your class code
>>> # meaning "the object that made this
>>> # call"
>>> # ...and it is the first argument to most
>>> # class methods!
>>> # (but you can then OMIT that first argument in
>>> # the call, if you use the obj.meth(args)
>>> # notation --- or, if you really want to,
>>> # you can also call it using classname.meth(obj, args)...!)
>>> # __repr__ - I OVERRIDE this (give it my
>>> # own method definition) when I want
>>> # to specify what the string
>>> # representation of my object should
>>> # look like
>>>
>>> # consider the classes Employee and Square
>>> # in lect09_6.py (also posted along with this session)
>>> import lect09_6
>>> from lect09_6 import *
>>> # (so I don't have to type lect09_6 in
>>> # front of my class names...)
>>> # here's how I create Employee and Square
>>> # objects...
>>> emp1 = Employee("Cleese",500)
>>> emp1.salary
500
>>> emp1.lastname
'Cleese'
>>> emp1.giveRaise(.03)
>>> emp1.salary
515.0
>>> emp2 = Employee("Palin", 740)
>>> emp1.giveRaise(.03)
>>> emp1.salary
530.45000000000005
>>> emp2.salary
740
>>> emp1.work()
Cleese does stuff
>>> emp2.work()
Palin does stuff
>>> # I did actually fix __repr__ in lecture - but I couldn't
>>> # see it until trying it in a new python session?!
>>> # (at least, it now works, after class!)
>>> # (guess there are limits to reload when you have
>>> # objects pre-existing of the class that has been reloaded?)
>>> # Reconstructing the actions above, here is now what str(emp1)
>>> # returns:
>>> str(emp1)
'<Employee: lastname=Cleese salary=$530.45>'
>>> # oops --- there's NOT a keyword new when creating a new
>>> # instance of a class in Python...!
>>> frame = new Square(4, "blue")
SyntaxError: invalid syntax
>>> frame = Square(4, "blue")
>>> frame
<Square: side_length=4 color=blue>
>>> str(frame)
'<Square: side_length=4 color=blue>'
>>> box = Square(3.56666, "purple")
>>> box
<Square: side_length=3 color=purple>
>>> # if I want a new class to be a subclass
>>> # of another ---
>>> # and to inherit that other class's
>>> # methods ---
>>> # I write:
>>> # class myNewClass(superclass1, superclass2, ...):
>>> # see lect09_7.py for Chef, a subclass of
>>> # Employee (yup, it should be posted with this
>>> # session, too)
>>> from lect09_7 import *
>>> cook = Chef("Lagasse", 5)
>>> cook.salary
50000
>>> # a Chef object inherits giveRaise from its superclass Employee!
>>> cook.giveRaise(.20)
>>> cook.salary
60000.0
>>> cook.work()
Lagasse makes food
>>> cook.maxMich
5
>>> cook.setMaxMich(10)
>>> cook.maxMich
10
>>>