Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Python: Class Extension, Exception Handling, Creating & Extending Classes, Schemes and Mind Maps of Object Oriented Programming

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

  • How can you enforce input validation in a class constructor using exceptions?
  • What is the role of the __str__() method in Python?
  • What are some common exceptions in Python and how can you handle them?
  • How do you define a class constructor in Python?
  • How do you extend an existing class in Python?

Typology: Schemes and Mind Maps

2021/2022

Uploaded on 09/27/2022

ekobar
ekobar 🇺🇸

4.3

(32)

261 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Class extension and
Exception handling
Genome 559
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Python: Class Extension, Exception Handling, Creating & Extending Classes and more Schemes and Mind Maps Object Oriented Programming in PDF only on Docsity!

Class extension and

Exception handling

Genome 559

Review - classes

1) Class constructors -

class myClass: def init(self, arg1, arg2): self.var1 = arg self.var2 = arg foo = myClass('student', 'teacher')

2) str() method and how Python print works

3) Other core Python class functions -

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()

Drosophila is an Insecta so it has all the Insecta data

structures and methods.

Drosophila is also an Animal so it has all the Animal data

structures and methods (and Eukaryote, though we didn't define

any).

What methods are available for an object of type Drosophila?

Writing a new Class by extension

Writing a class (review):

class Date:

def init(self, day, month, year):

Extending an existing class:

class HotDate(Date):

def init(self, day, month, year, toothbrush):

super(day, month, year)

self.bringToothbrush = toothbrush

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 , line X, in

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: catch the exception raised by the Date constructor

Exceptions - when to use

  • Any software that will be given to someone else,

especially if they don't know Python.

  • Private software that is complex enough to warrant.
  • Just as with code comments, exceptions are a useful

way of reminding yourself of what the program expects.

  • They have NO computational cost (if no exception is

thrown, nothing at all is computed).

Exercise 1

Write a program check_args.py that gets two command line

arguments and checks that the first represents a valid int

number and that the second one represents a valid float

number. Make useful feedback if they are not.

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

Challenge Exercises

Rewrite Exercise 2 using proper Exception handling.

Change your class definition from Exercise 2 so that it

provides useful traceback information so that you can find

where in your code you went wrong.