Your SlideShare is downloading. ×

Programming with Python - Week 3

447

Published on

Lecture Notes on Programming with Python.

Lecture Notes on Programming with Python.

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
447
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
10
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Transcript

    • 1. Programming withPython Week 3Dept. of Electrical Engineering and Computer ScienceAcademic Year 2010-2011
    • 2. Week 2 - Highlights• Dictionaries: {key:value,...}• Lists: [12,4,56,...]• Tuples: (firstname,lastname)=(“Programming”,”Python”)
    • 3. 4.1 The power ofIntrospection• Introspection is code looking at other modules and functions in memory as objects, getting information about them, and manipulating them.• Along the way: i. youll define functions with no name, ii. you’ll call functions with arguments out of order, iii. you’ll reference functions whose names you dont even know ahead of time.
    • 4. Introspection at workdef info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [method for method in dir(object) if callable(getattr(object, method))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList])
    • 5. (setup)• >>> import apihelper• >>> apihelper.info.__doc__ Print methods and doc strings.n n Takes module, class, list, dictionary, or string.
    • 6. 4.2 Using Optional andNamed Arguments• Python allows function arguments to have default values.• If the function is called without the argument, the argument gets its default value.• Arguments can be specified - in any order - by using named arguments.
    • 7. spacing and collapse areoptional arguments.def info(object, spacing=10, collapse=1):
    • 8. This looks totally whackeduntil you realize thatarguments are simply adictionary.• info(spacing=15, object=odbchelper)
    • 9. 4.3 Some built-in functions• type• str• dir• callable
    • 10. type function• The type function returns the datatype of any arbitrary object.• The possible types are listed in the types module. This is useful for helper functions that can handle several types of data.
    • 11. Examples• >>> type(apihelper) <type module>• >>> type(info) <type function>• >>> type("hello") <type str>• >>> type(1) <type int>
    • 12. types module• >>> import types• >>> types.ModuleType == type(apihelper) True
    • 13. str function• The str coerces data into a string. Every datatype can be coerced into a string.• >>> str(1) 1• >>> str(apihelper) "<module apihelper from .../Week 3/Code/ apihelper.py>"• >>> str([“mortal”, “kombat”, “go and fight”]) ask in class..
    • 14. dir function• dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.
    • 15. Examples• >>> dir([])• >>> dir({})• >>> dir(apihelper)
    • 16. callable function• The callable function takes any object and returns True if the object can be called, or False otherwise. example class• Callable objects include functions, class methods, even classes themselves.
    • 17. callable is beautiful:• By using the callable function on each of an objects attributes, you can determine which attributes you care about (methods, functions, classes) and which you want to ignore (constants and so on) without knowing anything about the object ahead of time. HINT: Introspection
    • 18. Examples• >>> import string• >>> string.punctuation !"#$%&()*+,-./:;<=>?@[]^_`{|}~• >>> string.join <function join at 0x6efaf0>• >>> callable(string.punctuation) False• >>> ask in class for string.join test..
    • 19. 4.4 Getting objectreferences with getattr• You already know that Python functions are objects.• What you dont know is that you can get a reference to a function without knowing its name until run-time, by using the getattr function.
    • 20. Examples• >>> li = [“Larry”, “Brackety”]• >>> li.pop• >>> getattr(li, “pop”)• >>> getattr(li, “append”)(“Junior”)• >>> li
    • 21. Ask in class..• 1. First import the ask_in_class module and then; 2. call the mockfunction using getattr function.
    • 22. 4.4.2 Introspection,Dispatching• what is the typical use of getattr-like functionality?
    • 23. Dispatching..
    • 24. Dispatcher
    • 25. Model, View, Controller (MVC)
    • 26. Model, View, Controller (MVC)So, what the hell is MVC?
    • 27. Dispatcher Dispatcher sitting here
    • 28. Model, View, Controller (MVC)
    • 29. Front Controller
    • 30. 4.4.2 Introspection,Dispatching• A common usage pattern of getattr is as a dispatcher.• For example, if you had a program that could output data in a variety of different formats, you could define separate functions for each output format and use a single dispatch function to call the right one.
    • 31. Example• For example, lets imagine a program that prints site statistics in HTML, XML, and plain text formats.• The choice of output format could be specified on the command line, or stored in a configuration file.• A statsout module defines three functions, output_html, output_xml, and output_text. Then the main program defines a single output function, like this:
    • 32. Example import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format) return output_function(data)
    • 33. Default valuein case, the method orattribute is not found. import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format, statsout.output_text) return output_function(data)
    • 34. 4.5 Filtering Lists• Python has powerful capabilities for mapping lists into other lists, via list comprehensions.• This can be combined with a filtering mechanism, where some elements in the list are mapped while others are skipped entirely.
    • 35. Filtering syntax:[mapping-expression for element in source-list if filter-expression] Any element for which the filter expression evaluates true will be included in the mapping. All other elements are ignored, so they are never put through the mapping expression and are not included in the output list.
    • 36. Example• >>> li = [“aaa”, “aa”, “a”, “b”]• >>> [elem for elem in li if len(elem) == 1]
    • 37. Ask in class..methodList = [method for method in dir(object) if callable(getattr(object, method))] interpretation please?!?
    • 38. 4.6 The Peculiar Nature of and and or• In Python, and and or perform boolean logic as you would expect, but they do not return boolean values; instead, they return one of the actual values they are comparing.
    • 39. and• If all values are true, the last value is returned.• If not all values are true, then it returns the first false value.• >>> “a” and “b” b• >>> “” and “b”
    • 40. or• if any value is true, that value is returned immediately.• if all values are false, then the last value is returned.
    • 41. 4.7 Using lambda functions• Python supports an interesting syntax that lets you define one-line mini-functions on the fly.• Borrowed from Lisp, these so-called lambda functions can be used anywhere a function is required.• The entire function can only be one expression.• A lambda is just an in-line function.
    • 42. Example• >>> def f(x): return x*2• >>> f(3)• >>> g = lambda x: x*2• >>> g(3)• >>> (lambda x: x*2)(3)
    • 43. Remember:• To generalize, a lambda function is a function that takes any number of arguments (including optional arguments) and returns the value of a single expression.• Dont try to squeeze too much into a lambda function; if you need something more complex, define a normal function instead and make it as long as you want.• Use them in places where you want to encapsulate specific, non-reusable code without littering your code with a lot of little one-line functions.
    • 44. apihelper.py
    • 45. Happy holidays

    ×