Unformatted text preview:

556CS 538 Spring 2008©Classes in PythonPython contains a class creationmechanism that’s fairly similar towhat’s found in C++ or Java.There are significant differencesthough:• All class members are public.• Instance fields aren’t declared.Rather, you just create fields asneeded by assignment (often inconstructors).• There are class fields (shared by allclass instances), but there are noclass methods. That is, all methodsare instance methods.557CS 538 Spring 2008©• All instance methods (includingconstructors) must explicitlyprovide an initial parameter thatrepresents the object instance. Thisparameter is typically called self.It’s roughly the equivalent of thisin C++ or Java.558CS 538 Spring 2008©Defining ClassesYou define a class by executing aclass definition of the formclass name: statement(s)A class definition creates a classobject from which class instancesmay be created (just like in Java).The statements within a classdefinition may be data members(to be shared among all classinstances) as well as functiondefinitions (prefixed by a defcommand). Each function musttake (at least) an initial parameterthat represents the class instancewithin which the function(instance method) will operate.For example,559CS 538 Spring 2008©class Example: cnt=1 def msg(self): print "Bo"+"o"*Example.cnt+"!"*self.n>>>Example.cnt1>>>Example.msg<unbound method Example.msg>Example.msg is unbound becausewe haven’t created any instancesof the Example class yet.We create class instances by usingthe class name as a function:>>> e=Example()>>> e.msg()AttributeError: n560CS 538 Spring 2008©We get the AttributeErrormessage regarding n because wehaven’t defined n yet! One way todo this is to just assign to it,using the usual field notation:>>> e.n=1>>> e.msg()Boo!>>>e.n=2;Example.cnt=2>>> e.msg()Booo!!We can also call an instancemethod by making the classobject an explicit parameter:>>> Example.msg(e)Booo!!It’s nice to have data membersinitialized when an object iscreated. This is usually done witha constructor, and Python allowsthis too.561CS 538 Spring 2008©A special method named__init__ is called whenever anobject is created. This methodtakes self as its first parameter;other parameters (possibly madeoptional) are allowed.We can therefore extend ourExample class with a constructor:class Example: cnt=1 def __init__(self,nval=1): self.n=nval def msg(self): print "Bo"+"o"*Example.cnt+ "!"*self.n>>>e=Example()>>> e.n1>>>f=Example(2)>>> f.n2562CS 538 Spring 2008©You can also define the equivalentof Java’s toString method bydefining a member functionnamed__str__(self).For example, if we adddef __str__(self): return "<%d>"%self.nto Example,then we can include Exampleobjects in print statements:>>> e=Example(2)>>> print e<2>563CS 538 Spring 2008©InheritanceLike any language that supportsclasses, Python allows inheritancefrom a parent (or base) class. Infact, Python allows multipleinheritance in which a classinherits definitions from morethan one parent.When defining a class you specifyparents classes as follows:class name(parent classes): statement(s)The subclass has access to itsown definitions as well as thoseavailable to its parents. Allmethods are virtual, so the mostrecent definition of a method isalways used.564CS 538 Spring 2008©class C: def DoIt(self): self.PrintIt() def PrintIt(self): print "C rules!"class D(C): def PrintIt(self): print "D rules!" def TestIt(self): self.DoIt() dvar = D() dvar.TestIt()D rules!565CS 538 Spring 2008©If you specify more than oneparent for a class, lookup isdepth-first, left to right, in the listof parents provided. For example,givenclass A(B,C): ...we first look for a non-localdefinition in B (and its parents),then in C (and its parents).566CS 538 Spring 2008©Operator OverloadingYou can overload definitions of allof Python’s operators to apply tonewly defined classes. Eachoperator has a correspondingmethod name assigned to it. Forexample,+ uses __add__, - uses__sub__, etc.567CS 538 Spring 2008©Givenclass Triple: def __init__(self,A=0,B=0,C=0): self.a=A self.b=B self.c=C def __str__(self): return "(%d,%d,%d)"% (self.a,self.b,self.c) def __add__(self,other):return Triple(self.a+other.a,self.b+other.b, self.c+other.c)the following codet1=Triple(1,2,3)t2=Triple(4,5,6)print t1+t2produces(5,7,9)568CS 538 Spring 2008©ExceptionsPython provides an exceptionmechanism that’s quite similar tothe one used by Java.You “throw” an exception by usinga raise statement:raise exceptionValueThere are numerous predefinedexceptions, includingOverflowError (arithmeticoverflow), EOFError (when end-of-file is hit), NameError (when anundeclared identifier isreferenced), etc.569CS 538 Spring 2008©You may define your ownexceptions as subclasses of thepredefined class Exception:class badValue(Exception): def __init__(self,val): self.value=valYou catch exceptions in Python’sversion of a try statement:try: statement(s)except exceptionName1, id1: statement(s)...except exceptionNamen, idn: statement(s)As was the case in Java, anexception raised within the trybody is handled by an exceptclause if the raised exceptionmatches the class named in the570CS 538 Spring 2008©except clause. If the raisedexception is not matched by anyexcept clause, the next enclosingtry is considered, or theexception is reraised at the pointof call.For example, using our badValueexception class, def sqrt(val): if val < 0.0: raise badValue(val) else: return cmath.sqrt(val)try: print "Ans =",sqrt(-123.0)except badValue,b: print "Can’t take sqrt of",b.valueWhen executed, we getAns = Can’t take sqrt of -123.0571CS 538 Spring 2008©ModulesPython contains a module featurethat allows you to access Pythoncode stored in files or libraries. Ifyou have a source file mydefs.pythe command import mydefswill read in all the definitionsstored in the file. What’s read incan be seen by executingdir(mydefs)To access an imported definition,you qualify it with the name ofthe module. For example,mydefs.fctaccesses fct which is defined inmodule mydefs.572CS 538 Spring 2008©To avoid explicit qualification youcan use the commandfrom modulename import id1, id2,...This makes id1, id2, ... availablewithout qualification. Forexample,>>> from test import sqrt>>> sqrt(123)(11.0905365064+0j)You can use the commandfrom modulename import *to import (without qualification)all the definitions in modulename.573CS 538


View Full Document

UW-Madison COMPSCI 538 - Lecture 40 Notes

Download Lecture 40 Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 40 Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 40 Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?