Exploration Seminar 7 Python Objects Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.02 Exceptions raise type(message) raise Exception(message) Exceptions AssertionError TypeError NameError ValueError IndexError SyntaxError ArithmeticError http://docs.python.org/library/exceptions.html#bltin-exceptions3 Class Syntax • Recall the syntax for making a basic class example.py 1 2 3 4 5 6 7 8 9 class ClassName: def __init__(self, params, ...): self.field1 = value self.fieldn = value #Your code here def other_methods(self, params, ...): #your code here4 Implicit Parameter • The first parameter is a reference to the current instance of the defining class. • You do not pass it yourself, rather Python passes it for you when you invoke an instance method. example.py 1 2 def __init__(self, params, ...):5 Inheritance • Python has multiple inheritance • This means that we can create a class that subclasses several classes • Python makes an effort to mix super classes – Searches super classes from left to right – We can disambiguate if there are problems with this example.py 1 2 class ClassName(SuperClass1, SuperClass2, ...): def __init__(self, params, ...):6 Commenting Your Classes • Classes and functions have a built-in field called __doc__ • We can use this as a way to get more bang for our comments • These __doc__ fields could be used like JavaDoc example.py 1 2 3 4 class Point(): “““This class defines a point in 2D space””” def __init__(self, x, y): “““Post: returns a Point with the given x and y fields”””7 Name Mangling • Python does not have private methods • Python does have name mangling, any method that starts with 2+ underscores and does not end in 2+ underscores with be renamed to _classname__method example.py 1 2 3 4 5 6 7 8 9 class Foo(): def __init__(self): self.__helper() def __helper(self): print(“sneaky”) x = Foo() #output: sneaky x._Foo__helper() #output: sneaky x.__helper() #output: AttributeError8 Static Fields • There is a subtle difference between declaring fields in the class and declaring them in the constructor • Fields defined in the class can be used as static variables, meaning they belong to the class as a whole example.py 1 2 3 4 5 6 7 class MovieTicket(): basePrice = 10 def __init__(self, fee): self.price = self.basePrice + fee x = MovieTicket(5) print(x.price) #result: 15 print(MovieTicket.basePrice) #result: 109 Static Methods • We can use decorators to tell our function to be static, meaning they belong to the class, not an instance example.py 1 2 3 4 5 6 7 8 9 10 11 class Point(): def __init__(self, x, y): self.x = x self.y = y @staticmethod def distance(p1, p2): d = sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2 ) return d x = Point(0, 0) y = Point(0, 5) print(Point.distance(x, y)) #result: 510 Class Methods • A class method receives a reference to the class instead of a reference to an instance • You can use this class parameter (cls) to reference the static variables or methods • One use of this ability is writing documentation methods11 Class Methods example.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Point(): """This class defines a point in 2D space.""" def __init__(self, x, y): """Post: returns a Point with coordinates (x,y)""" self.x = x self.y = y @classmethod def help(cls): for attr in cls.__dict__: print(str(attr) + ": " + cls.__dict__ [attr].__doc__)#result: 5 x = Point(0, 0) x.help()12 __str__() • We already know about the __str__() method that allows a class to convert itself into a string rectangle.py 1 2 3 4 5 6 7 8 9 class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"13 First Class Citizens • For built-in types like ints and strings we can use operators like + and *. • Our classes so far were forced to take back routes and use methods like add() or remove() • Python is super cool, in that it allows us to define the usual operators for our class • This brings our classes up to first class citizen status just like the built in ones14 Underscored methods • There are many other underscored methods that allow the built-in function of python to work • Most of the time the underscored name matches the built-in function name Built-In Class Method str() __str__() len() __len__() abs() __abs__()15 Underscored methods • There are underscore methods that you can implement in order to define logical operations and arithmetic operations Operator Class Method - __sub__(self,other) + __add__(self, other) * __mul__(self, other) / __truediv__(self, other) Binary Operators Comparison Operators Unary Operators Operator Class Method - __neg__(self) + __pos__(self) Operator Class Method == __eq__(self,other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) N/A __nonzero__(self) http://docs.python.org/reference/datamodel.html#sequence-types16 Vector Class Lets write a class that represents a Vector. A Vector is a Point that has some extra functionality. We should be able to add and subtract two Vectors, determine if two Vectors are equal. We should be able to multiply a Vector by a scalar and ask what the Vectorʼs length is as an integer. In addition, Vectors should have these methods and fields. Method/Field Functionality origin The origin as a field isDiagonalInPointSet() Returns whether this Vector lies on the diagonal and is contained in the given point set slope() Returns the slope between the two given
View Full Document