Your SlideShare is downloading. ×
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Python & Perl: Lecture 15
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Python & Perl: Lecture 15

680

Published on

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

  • Be the first to like this

No Downloads
Views
Total Views
680
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
0
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

Transcript

  • 1. Python & Perl Lecture 15 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  • 2. Outline ● Introspection ● Nothing Magic about SELF ● Exception Handlingwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 3. Announcement ● Midterm will be on Thursday, March 08, 8:45am to 10:30am, online ● Midterm will be coding ● It will be posted online at 8:45am ● It will be due in your Dropbox at 10:30amwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 4. Introspectionwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 5. Multiple Inheritance Example class Calculator: def calculate(self, expression): self.value = eval(expression) class Talker: def talk(self): print My value is, self.value class TalkingCalculator(Calculator,Talker): passwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 6. Interfaces & Introspection ● An objects interface is a set of methods and attributes known to the world ● There is no way in Python to formally define interfaces ● Introspection is a process of checking whether objects have specific methods and attributeswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 7. Introspection with hasattr() ## hasattr checks if an attribute is ## present >>> hasattr(tc, talk) True >>> hasattr(tc, name) Falsewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 8. Introspection with getattr() ## getattr gets an attribute of an object >>> getattr(tc, talk, None) <bound method TalkingCalculator.talk of <__main__.TalkingCalculator object at 0x01FAAB30>> >>> getattr(tc, address, None) >>>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 9. Introspection with callable() ## check if an attribute is a callable object >>> callable(getattr(tc, talk, None)) True >>> callable(getattr(tc, name, None)) False >>> callable(getattr(tc, address, None)) Falsewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 10. Adding Attributes with setattr() ## You can add new attributes to objects >>> hasattr(tc, name) False >>> setattr(tc, name, Talking Calc 1.0) >>> hasattr(tc, name) True ## You can get a dictionary of attributes >>> tc.__dict__ {name: Talking Calc 1.0, value: 3}www.youtube.com/vkedco www.vkedco.blogspot.com
  • 11. inspect Module ● This module provides tools to get information about live objects such as modules, classes, methods, functions, tracebacks (stack traces), frame objects, and code objects ● The module provides four principal services: – Type checking – Getting source code – Class and function inspection – Examination of the interpreter stackwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 12. inspect.getmembers() ## object browsing with inspect >>> import inspect ## this returns an comprehensive list of members ## of a given object >>> inspect.getmembers(tc) ## returns a dictionary of attributes >>> tc.__dict__www.youtube.com/vkedco www.vkedco.blogspot.com
  • 13. inspect.getsource() ## You can get the source code of ## objects methods >>> inspect.getsource(getattr(tc, talk)) " def talk(self):n print My value is, self.valuen" >>> inspect.getsource(getattr(tc, calculate)) def calculate(self, expression):n self.value = eval(expression)nwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 14. Nothing Magic About SELFwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 15. Example class Person: def setName(self, name): self.name = name def getName(self): return self.name def greet(self): print "Hello, I am %s." % self.namewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 16. Example >>> p1 = Person() # p1 is instance of Person >>> p2 = Person() # p2 is instance of Person >>> p1.setName(John) >>> p2.setName(Bob) >>> p1.getName() John >>> p2.getName() Bob >>> p1.name Johnwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 17. Same Implementation without SELF class Person2: def setName(x, name): x.name = name def getName(x): return x.name def greet(x): print "Hello, I am %s." % x.namewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 18. Another Implementation without SELF class Person2: def setName(this, name): this.name = name def getName(this): return this.name def greet(this): print "Hello, I am %s." % this.namewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 19. Conclusion ● There is nothing magic about self: self is just an argument name ● Any other legal Python argument name (e.g., x or this or it) can be used as the first argument in method argument listswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 20. Exception Handlingwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 21. Exceptions ● Exception is a run-time condition that signals an error, an unexpected event, or an event that must be handled in a special way ● When a code segment (e.g. a function or a method) does not know how to handle an event, it may raise/throw an exception ● If an exception is handled, the program may continue to run ● If an exception is not handled, the program terminateswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 22. Example 1 def add2(x, y): return x + y >>> add2(1, 2) 3 >>> add2(a, b) ab ### this call raises a run time TypeError Exception >>> add2(a, 1) TypeError: cannot concatenate str and int objectswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 23. Example 2 ## try adding x and y and if a TypeError object is raised ## by x + y, bind it to the variable e and print it def add2e(x, y): try: return x + y except TypeError, e: print ewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 24. Example 3 ## add2e just prints an exception object we can take a more principled approach ## by converting both argument values into strings and then adding them def add2e_handle_type_error(x, y): xstr, ystr = None, None if not isinstance(x, str): xstr = str(x) else: xstr = x if not isinstance(y, str): ystr = str(y) else: ystr = y return xstr + ystrwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 25. Example 3 ## add2e02 always returns a value: a TypeError ## exception is handled ## Since we do not use the TypeError object, we do not ## bind it to any variable in the except clause def add2e02(x, y): try: return x + y except TypeError: return add2e_handle_type_error(x, y)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 26. Catching Multiple Exceptions ● It is possible to catch multiple exceptions def div2(): xstr = raw_input(Enter 1st number: ) ystr = raw_input(Enter 2nd number: ) try: x = float(xstr) y = float(ystr) return x/y except ValueError: print Cannot convert one of the inputs into a float except ZeroDivisionError: print Cannot divide by 0www.youtube.com/vkedco www.vkedco.blogspot.com
  • 27. Multiple Exception Refinement ● Exception handling in div2() can be refined ● There is no need to ask for the second input if the first input cannot be converted into a float ● There is no need to divide if the second input cannot be converted into a floatwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 28. Multiple Exception Refinement def div2_v2(): try: xstr = raw_input(Enter 1st number: ) x = float(xstr) except ValueError: print Cannot convert input into float else: try: ystr = raw_input(Enter 2nd number: ) y = float(ystr) except ValueError: print Cannot convert input into float else: try: return x/y except ZeroDivisionError: print Cannot divide by 0www.youtube.com/vkedco www.vkedco.blogspot.com
  • 29. Catching Multiple Exceptions ● There are situations when you know what exceptions a code segment may raise but you do not care which one of them is raised def div2_v3(): xstr = raw_input(Enter 1st number: ) ystr = raw_input(Enter 2nd number: ) try: x = float(xstr) y = float(ystr) return x/y except ValueError, ZeroDivisionError: print Either wrong value type or zero divisionwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 30. Example def div2_v4(): xstr = raw_input(Enter 1st number: ) ystr = raw_input(Enter 2nd number: ) try: x = float(xstr) y = float(ystr) return x/y except Exception, e: ## this catches any exception print e, type(e)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 31. Example ● Discovering that the code segment raises a ValueError >>> div2_v4() Enter 1st number: 1 Enter 2nd number: a could not convert string to float: a <type exceptions.ValueError> ● Discovering that the code segment raises a ZeroDivisionError >>> div2_v4() Enter 1st number: 1 Enter 2nd number: 0 float division by zero <type exceptions.ZeroDivisionError>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 32. Getting Valid User Input ● It is possible to force the user input entering valid input (e.g. password) by going into an infinite loop and breaking only after valid input has been entered and processed while True: ask for input do something with it except: ## this is a catch all clause print Invalid input. Please try again else: breakwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 33. Example password = abc123 def verify_password(): while True: try: p = raw_input(Enter password: ) if p != password: raise Exception ## password mismatch, so raise an exception except: print Password invalid. Try again. else: print Logging in... print Welcome! breakwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 34. Finally, Cleanup! ● When a code segment allocates a lot resources, it is worth it to clean up those resources in case an exception is raised Image im = Image.open(/home/vladimir/images/im_01.bmp) try: ## do some heavy duty, exception prone processing of im except Exception, e: print e, type(e) finally: ## finally clause is guaranteed to be called del imwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 35. Exception Propagation ● If a function is called by a caller and throws an exception, the caller can either handle that exception or not ● If the exception is not handled, it propagates to the caller of the caller and then to the caller of the caller of the caller and so on ● This exception propagation continues until the exception reaches the global scope of the running program ● If there is no handler in the global scope, the program terminates with a stack tracewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 36. Example ● We define four functions that raise four difference types of exceptions def raise_value_error(): raise ValueError(ValueError) def raise_eof_error(): raise EOFError(EOFError) def raise_arithmetic_error(): raise ArithmeticError(ArithmeticError) def raise_environment_error(): raise EnvironmentError(EnvironmentError)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 37. Example ● We define another handler that handles three types of exceptions except EnvironmentError def top_handler(handle_error, raise_error): try: handle_error(raise_error) except ValueError, e: print e, handled by top_handler except EOFError, e: print e, handled by top_handler except ArithmeticError, e: print e, handled by top_handlerwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 38. Example ● EOFError is handled by handle_eof_error >>> top_handler(handle_eof_error, raise_eof_error) EOFError handled by its handler ● ValueError is propagated from handle_eof_error to top_handler where it is handled >>> top_handler(handle_eof_error, raise_value_error) ValueError handled by top_handler ● EnvironmentError propagates to the global scope and cause the program to terminate with a stack trace >>> top_handler(handle_eof_error, raise_environment_error) Traceback (most recent call last): EnvironmentError: EnvironmentErrorwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 39. Reading & References ● www.python.org ● Ch 07 M. L. Hetland. Beginning Python From Novice to Pro- nd fessional, 2 Ed., APRESS ● Ch 08 M. L. Hetland. Beginning Python From Novice to Pro- fessional, 2nd Ed., APRESSwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 40. Feedback Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco www.vkedco.blogspot.com

×