Download presentation
Presentation is loading. Please wait.
1
Classes and Objects – digging deeper
Victor Norman CS104
2
Reading Quiz
3
Vector class Suppose we want a 2D Vector “type”.
What do we need to store? (what attributes?) x, y What operations do we need to be able to do? set and get x, y normalize get magnitude scale add 2 Vectors cross products, dot products, …
4
Write constructor for Vector
Write the constructor, which takes params x and y, with default values 0 and 0. class Vector: def __init__(self, x=0, y=0): self._x = x self._y = y constructor
5
Write getters and setters
Write the getter and setter for x attribute. class Vector: … def getX(self): return self._x def setX(self, newX): self._x = newX accessor mutator
6
Write getMagnitude() Magnitude is distance of x, y from 0, 0.
class Vector: … def getMagnitude(self): return (self._x * self._x + self._y * self._y) ** 0.5
7
Write normalize() class Vector: … def normalize(self): mag = self.getMagnitude() self._x /= mag self._y /= mag
8
Use it Create a Vector pointing to 16, 12. vect = Vector(16, 12)
print the vector’s x and y values print(vect.getX(), vect.getY()) print the magnitude of the vector print(vect.getMagnitude()) normalize the vector vect.normalize()
9
Printing a Vector Would be nice to be able to tell a vector object to convert itself to a string representation. Can be done by defining __str__ in the class, so that: print(vect) calls str(vect) calls (which happens automatically) vect.__str__() automatically. __str__ must return a string representation of the object.
10
Code for __str__ Suppose we want a vector to be printed this way:
---16, 12--> class Vector: … def __str__(self): return (“---“ + str(self._x) + “, “ str(self._y) + “-->”)
11
Adding two vectors. What if we want to add two vectors together?
vect1 = Vector(16, 12) vect2 = Vector(-12, -16) res = vect1 + vect2 print(res) + is defined for integers, floats, strings, but python can’t just add two Vector objects together without being told how.
12
Defining __add__ for op1 + op2, intepreter looks at type of op1, and looks if __add__ is defined for it. If it is, it calls it, passing op2 as the 2nd parameter. It returns a new Vector object. class Vector: … def __add__(self, op2): return Vector(self.getX() + op2.getX(), self.getY() + op2.getY())
13
Other built-in operations
__sub__ __mul__ __len__ __int__ __cmp__: for doing ==, <, <=, >, >=, !=, etc. etc.!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.