week 2 quick and dirty jython refresher
play

Week 2: Quick and Dirty Jython Refresher (Prelude to Asynchronous - PowerPoint PPT Presentation

Week 2: Quick and Dirty Jython Refresher (Prelude to Asynchronous Programming) CS6452 Connecting the Lo-Fi Prototype with the Project A few points about the IM assignment The IM protocol well be using doesnt support


  1. Week 2: Quick and Dirty Jython Refresher (Prelude to Asynchronous Programming) CS6452

  2. Connecting the Lo-Fi Prototype with the Project  A few points about the IM assignment The IM protocol we’ll be using doesn’t support   Authentication/login  Sending messages to a user before that user joins the chat  Named, persistent chat rooms  Status changes (”available”, “away”)  Buddies  Adding people to existing chats Some of these you can implement in your own client, even without  server support  E.g., buffer messages sent to a user before he/she joins

  3. A Bit More Administrivia...  Late policy for assignments: Clear with me first if you have a valid excuse for missing a due date   Examples: medical or family emergency My policy is -10% per late day, maximum 3 days late   Grading criteria will be posted on the web for each assignment  Readings will be posted ~1 week in advance So, readings we’ll discuss next week are already up  Reminder: 1-page summaries are due one in class one week after  readings are assigned!  In-class presentations For each module we’ll do a set of short in-class presentations  Drop me a note if you want to present on the GUI project (9/18) 

  4. Today’s Menu  Jython Refresher Collection Classes  Scoping and Modules  Classes and Objects  GUI Programming   Useful odds-and-ends that may come in handy for the next assignment

  5. Jython Collection Classes

  6. Collections  One of the strongest features of Jython: powerful built-in data structures  Let you organize and retrieve collections of data in ways that would be impractical if you had to stash every item in a variable  Sequences Lists  Tuples   Dictionaries

  7. Variables and References  A variable is simply a name that contains a reference to some information  foo = “Hello, world” String “Hello, world” foo  Variables can be reassigned, and multiple variables can refer to the same thing.  Stashing a reference in a variable gives you a way to name it, and get at it later.

  8. The Need for More Complex Data Structures  Some more complex structures are hard to represent by just a named variable though.  Example: you want to keep track of all of the users in a chat. user1 = “Steven”  user2 = “Amy”  ...   This is too static . Would you just create 1000 variables in case you ever had that many users? How would you do something to each one (can’t easily iterate)

  9. Lists to the Rescue  Fortunately, Jython has a build in way to do this: lists  foo = [ “one”, “two”, “three” ] List foo  Lists collect multiple references to data items into a single data structure  These references are ordered  The contents of the list can be altered (it is mutable )  currentChatUsers = [ “Amy”, “Steven”, ... ]

  10. A Quick Jython List Refresher  Lists are ordered collections of items >>> L=[0, ‘zero’, ‘one’, 1]  Selecting items from a list (note indices start at 0!) >>> print L[1] ‘zero’  Getting the length of a list >>> len(L) 4  Modifying lists >>> L.append(’two’) >>> L.remove(’zero’) >>> print L [0, ‘one’, 1, ‘two’]  Iteration for item in L: print item

  11. Tuples: Fixed Sequences  Like lists, only immutable The set of references in a tuple is fixed   Generally used either when: You need a constant list  daysOfWeek = ( “Monday,” “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” )  You need to group together a set of data whose structure is fixed:   E.g., using tuples as quick-and-dirty records, such as address book entries: myContactInfo = ( “Keith Edwards”, “TSRB348”, “keith@cc” )   All list operations work on tuples, except ones that modify the set of references within the tuple So, no append(), remove(), etc. 

  12. Associating Data Items With Each Other  Sometimes, you need to associate one item with another one Example: hours worked on each day of the week:  “Sunday” 4.5 “Monday” 8 ... ...  You could do this with variables, as long as there’s a fixed set of them: sunday=4.5  monday=8 

  13. Associating Data Items With Each Other (cont’d)  If you don’t know the associations you might have up front, you could use parallel lists: workDates = [ “1/29/05”, “1/30/05”, “2/1/05”, ... ]  workHours = [ 4.5, 8, 5.5, ... ]   Then, iterate through the first list to find the date you’re looking for, then look for the item with the corresponding index in the second list  Too much work! Too error prone!  Fortunately, Jython has a built-in data structure for creating associations: the dictionary

  14. The Dictionary Data Structure  Dictionaries associate values with keys (you lookup a value given its key)  Both are references to data items  workRecord = { “1/29/05”: 4.5, “1/30/05”: 8, “2/2/05”: 5.5 } Dictionary “1/29/05” 4.5 “1/30/05” 8.0 workRecord “2/2/05” 5.5  Dictionaries are the most commonly used Jython data type  Virtually any Jython data type can be used as a key or as a value

  15. A Quick Jython Dictionary Refresher  Initializing a dictionary: >>> dict = {’one’: 1, ‘two’: 2, ‘three’: 3}  Looking up values: >>> dict[”two”] 2  Inserting and changing values: >>> dict[”four”] = 4 >>> dict[”two”] = 2222 >>> dict {’one’:1, ‘two’: 2222, ‘three’: 3, ‘four’: 4}  Other operations: >>> del dict[”one”] >>> len(dict) 3

  16. More Dictionary Goodness  Testing whether or not a dictionary has a given key >> dict.has_key(“two”) 1 >> dict.has_key(“five”) 0  Getting keys, values, and entire items >> dict.keys() [“two”, “three”, “four”] >> dict.values() [2222, 3, 4] >> dict.items() [(“two”, 2222), (“three”, 3), (“four”, 4)]

  17. Scoping and Modules

  18. Scoping  What is scoping?  Scoping is a fancy word that just means “the rules about what you can see from where” in a program  The namespace is the collection of stuff that you can see from any given point in a program

  19. An Example: Scoping Error  welcomeMsg = “Hello!”  def changeWelcomeMsg(): welcomeMsg = “Bonjour!”  print “New welcome message is”, welcomeMsg   changeWelcomeMsg()  >>> New welcome message is Bonjour!  print welcomeMsg  “Hello!”

  20. An Example: Scoping Error  welcomeMsg = “Hello!” welcomeMsg is defined in the global scope  def changeWelcomeMsg(): welcomeMsg = “Bonjour!” This lines defines a new variable  with the same name, in the local scope! print “New welcome message is”, welcomeMsg   changeWelcomeMsg()  >>> New welcome message is Bonjour!  print welcomeMsg Since this call to print is outside the function changeWelcomeMsg(), it  “Hello!” refers to the welcomeMsg variable in the global scope.

  21. Thinking About Scopes  Variables named in the global scope are available to statements in any global scope scope Unless they have been “hidden” by a func1 local scope  local variable with the same name, as in the error example  Variables named in a local scope are func2 local scope only available to statements in that scope  The first assignment to a variable func3 local scope determines the scope it is in

  22. More on Scopes  “Global” really means the file the variable is in When you start developing with multiple files, each file defines its own  scope that is “global” for that file  Each call to a function creates a new local scope Thus if a variable foo is defined in function func(), each call to func() has  its own new “namespace” and its own separate foo  By default, all assignments that you make in a function create names in the local scope Advanced: you can use the global statement if you want to change a  global variable from within a function Dangerous, but useful. We’ll talk about it in a later lecture   Names not assigned to in a function are assumed to be globals

  23. Still More on Scopes  What all this boils down to is... Local variables (those first assigned to within a function) serve as  temporary names you need only when a function is running This helps modularity of your program (”hide” details within a  function)  But: You need to be careful when using a name within a function that’s  defined outside Subtle and hard to track bugs... 

  24. Scoping Gotchas  Subtly different than some other languages  1. Local scopes don’t nest def outerfunc(x, y): def innerfunc(z): if z > 0: print x, y innerfunc(x) x and y aren’t available inside the local scope for innerfunc   2. There are actually three scopes: global, local, and __builtin__ First, the local scope is checked  Then, the global scope  Finally, the scope defined by the module called __builtin__   len, abs, max, min, ...

Recommend


More recommend