












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An overview of class extension and exception handling in Python. It covers the basics of class constructors, the __str__() method, and core Python class functions. The document then explains how to extend existing classes using the extension mechanism. Additionally, it discusses exception handling, including how to enforce input validation in a class constructor using exceptions.
What you will learn
Typology: Schemes and Mind Maps
1 / 20
This page cannot be seen from the preview
Don't miss anything!
class myClass: def init(self, arg1, arg2): self.var1 = arg self.var2 = arg foo = myClass('student', 'teacher')
add() # used for the '+' operator mul() # used for the '*' operator sub() # used for the '-' operator etc.
Extension formalism – much like biological classification
class Eukaryote
class Animal (extends Eukaryote) add class method movementRate()
class Insecta (extends Animal) add class method numberOfWings()
class Drosophila (extends Insecta) add class method preferredFruit()
Writing a new Class by extension
ALL OF THE DATA TYPES AND METHODS WRITTEN
FOR Date ARE NOW AVAILABLE!
class to extend
super - call the con- structor for Date
Exception Handling
What if you want to enforce that a Date has integer
values for day, month, and year?
class Date: def init(self, day, month, year): self.day = day self.month = month self.year = year
myDate = Date("Ides", "March", "XLIV BC")
Does this code crash?
import sys
intval = int(sys.argv[1])
How could you check that the user entered a valid argument?
Checking command line arguments
import sys
try: intval = int(sys.argv[1]) except: print "first argument must be parseable as an int value" sys.exit()
two new reserved key words - try and except
class Date: def init(self, day, month, year): try: self.day = int(day) except ValueError: print 'Date constructor: day must be an int value' try: self.month = int(month) except ValueError: print 'Date constructor: month must be an int value' try: self.year = int(year) except ValueError: print 'Date constructor: year must be an int value'
Example - enforcing format in the Date class
indicates only catches this type of exception
FYI, if there are other types of exceptions, they will be reported by the default Python exception handler, with output you are very familiar with, e.g.: Traceback (most recent call last): File
import traceback import sys
class Date: def init(self, day, month, year): try: self.day = int(day) except ValueError: print 'Date constructor: day must be an int value' traceback.print_exc() sys.exit()
You may even want to force a program exit with information about the offending line of code:
special traceback function that prints other information for the exception
Using your own Exceptions
class Date: def init(self, day, month, year): try: self.day = int(day) except: raise DayFormatException
raise is a new reserved key word - it raises an exception. The DayFormatException will get returned to whereever the constructor was called - there it can be "caught"
try: myDate = Date("Ides", "March", "IXIV") except:
Exceptions - when to use
especially if they don't know Python.
way of reminding yourself of what the program expects.
thrown, nothing at all is computed).
python check_args.py 3 help! help! is not a valid second argument, expected a float value python check_args.py I_need_somebody 3. I_need_somebody is not a valid first argument, expected an int value
import sys
try: arg1 = int(sys.argv[1]) except ValueError: print "'sys.argv[1]' is not a valid first argument, expected an int value" sys.exit() try: arg2 = int(sys.argv[2]) except ValueError: print "'sys.argv[2]' is not a valid second argument, expected a float value" sys.exit()
import sys import re class fastaDNA: init(self, name, sequence): self.name = name match = re.match('[^ACGTNacgtn]') if match != None: print sequence, 'is an invalid DNA sequence' sys.exit() self.sequence = sequence