In [ ]:
from __future__ import print_function

Classes

Classes are the fundamental concept for object oriented programming. A class defines a data type with both data and functions that can operate on the data. An object is an instance of a class. Each object will have its own namespace (separate from other instances of the class and other functions, etc. in your program).

We use the dot operator, ., to access members of the class (data or functions). We've already been doing this a lot, strings, ints, lists, ... are all objects in python.

simplest example: just a container (like a struct in C)


In [ ]:
class Container(object):
    pass
        
a = Container()
a.x = 1
a.y = 2
a.z = 3

b = Container()
b.xyz = 1
b.uvw = 2

print(a.x, a.y, a.z)
print(b.xyz, b.uvw)

notice that you don't have to declare what variables are members of the class ahead of time (although, usually that's good practice).

Here, we give the class name an argument, object. This is an example of inheritance. For a general class, we inherit from the base python object class.

More useful class

Here's a class that holds some student info


In [ ]:
class Student(object):
    def __init__(self, name, grade=None):
        self.name = name
        self.grade = grade

Let's create a bunch of them, stored in a list


In [ ]:
students = []
students.append(Student("fry", "F-"))
students.append(Student("leela", "A"))
students.append(Student("zoidberg", "F"))
students.append(Student("hubert", "C+"))
students.append(Student("bender", "B"))
students.append(Student("calculon", "C"))
students.append(Student("amy", "A"))
students.append(Student("hermes", "A"))
students.append(Student("scruffy", "D"))
students.append(Student("flexo", "F"))
students.append(Student("morbo", "D"))
students.append(Student("hypnotoad", "A+"))
students.append(Student("zapp", "Q"))

Quick Exercise:

Loop over the students in the students list and print out the name and grade of each student, one per line.



In [ ]:

We can use list comprehensions with our list of objects. For example, let's find all the students who have A's


In [ ]:
As = [q.name for q in students if q.grade.startswith("A")]
As

Playing Cards

here's a more complicated class that represents a playing card. Notice that we are using unicode to represent the suits.

unicode support in python is also one of the major differences between python 2 and 3. In python 3, every string is unicode.


In [ ]:
class Card(object):
    
    def __init__(self, suit=1, rank=2):
        if suit < 1 or suit > 4:
            print("invalid suit, setting to 1")
            suit = 1
            
        self.suit = suit
        self.rank = rank
        

    def value(self):
        """ we want things order primarily by rank then suit """
        return self.suit + (self.rank-1)*14
    
    # we include this to allow for comparisons with < and > between cards 
    def __lt__(self, other):
        return self.value() < other.value()

    def __unicode__(self):
        suits = [u"\u2660",  # spade
                 u"\u2665",  # heart
                 u"\u2666",  # diamond
                 u"\u2663"]  # club
        
        r = str(self.rank)
        if self.rank == 11:
            r = "J"
        elif self.rank == 12:
            r = "Q"
        elif self.rank == 13:
            r = "K"
        elif self.rank == 14:
            r = "A"
                
        return r +':'+suits[self.suit-1]
    
    def __str__(self):
        return self.__unicode__()  #.encode('utf-8')

When you instantiate a class, the __init__ method is called. Note that all method in a class always have "self" as the first argument -- this refers to the object that is invoking the method.

we can create a card easily.


In [ ]:
c1 = Card()

We can pass arguments to __init__ in when we setup the class:


In [ ]:
c2 = Card(suit=1, rank=13)

Once we have our object, we can access any of the functions in the class using the dot operator


In [ ]:
c1.value()

In [ ]:
c3 = Card(suit=0, rank=4)

The __str__ method converts the object into a string that can be printed. The __unicode__ method is actually for python 2.


In [ ]:
print(c1)
print(c2)

the value method assigns a value to the object that can be used in comparisons, and the __lt__ method is what does the actual comparing


In [ ]:
print(c1 > c2)
print(c1 < c2)

Note that not every operator is defined for our class, so, for instance, we cannot add two cards together:


In [ ]:
c1 + c2

Quick Exercise:

  • Create a "hand" corresponding to a straight (5 cards of any suite, but in sequence of rank)
  • Create another hand corresponding to a flush (5 cards all of the same suit, of any rank)
  • Finally create a hand with one of the cards duplicated—this should not be allowed in a standard deck of cards. How would you check for this?


In [ ]:

Deck of Cards

classes can use other include other classes as data objects—here's a deck of cards. Note that we are using the python random module here.


In [ ]:
import random

class Deck(object):
    """ the deck is a collection of cards """

    def __init__(self):

        self.nsuits = 4
        self.nranks = 13
        self.minrank = 2
        self.maxrank = self.minrank + self.nranks - 1

        self.cards = []

        for rank in range(self.minrank,self.maxrank+1):
            for suit in range(1, self.nsuits+1):
                self.cards.append(Card(rank=rank, suit=suit))

    def shuffle(self):
        random.shuffle(self.cards)

    def get_cards(self, num=1):
        hand = []
        for n in range(num):
            hand.append(self.cards.pop())

        return hand
    
    def __str__(self):
        string = ""
        for c in self.cards:
            string += str(c) + " "
        return string

let's create a deck, shuffle, and deal a hand (for a poker game)


In [ ]:
mydeck = Deck()
print(mydeck)
print(len(mydeck.cards))

notice that there is no error handling in this class. The get_cards() will deal cards from the deck, removing them in the process. Eventually we'll run out of cards.


In [ ]:
mydeck.shuffle()

hand = mydeck.get_cards(5)
for c in sorted(hand): print(c)

Operators

We can define operations like + and - that work on our objects. Here's a simple example of currency—we keep track of the country and the amount


In [ ]:
class Currency(object):
    """ a simple class to hold foreign currency """
    
    def __init__(self, amount, country="US"):
        self.amount = amount
        self.country = country
        
    def __add__(self, other):
        return Currency(self.amount + other.amount, country=self.country)
    
    def __str__(self):
        return "{} {}".format(self.amount, self.country)

We can now create some monetary amounts for different countries


In [ ]:
d1 = Currency(10, "US")
d2 = Currency(15, "US")
print(d1 + d2)

Quick Exercise:

As written, our Currency class has a bug—it does not check whether the amounts are in the same country before adding. Modify the __add__ method to first check if the countries are the same. If they are, return the new Currency object with the sum, otherwise, return None.



In [ ]:

Vectors Example

Here we write a class to represent 2-d vectors. Vectors have a direction and a magnitude. We can represent them as a pair of numbers, representing the x and y lengths. We'll use a tuple internally for this

We want our class to do all the basic operations we do with vectors: add them, multiply by a scalar, cross product, dot product, return the magnitude, etc.

We'll use the math module to provide some basic functions we might need (like sqrt)

This example will show us how to overload the standard operations in python. Here's a list of the builtin methods:

https://docs.python.org/3/reference/datamodel.html

To make it really clear what's being called when, I've added prints in each of the functions


In [ ]:
import math

In [ ]:
class Vector(object):
    """ a general two-dimensional vector """
    
    def __init__(self, x, y):
        print("in __init__")
        self.x = x
        self.y = y
        
    def __str__(self):
        print("in __str__")        
        return "({} î + {} ĵ)".format(self.x, self.y)
    
    def __repr__(self):
        print("in __repr__")        
        return "Vector({}, {})".format(self.x, self.y)

    def __add__(self, other):
        print("in __add__")        
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        else:
            # it doesn't make sense to add anything but two vectors
            print("we don't know how to add a {} to a Vector".format(type(other)))
            raise NotImplementedError

    def __sub__(self, other):
        print("in __sub__")        
        if isinstance(other, Vector):
            return Vector(self.x - other.x, self.y - other.y)
        else:
            # it doesn't make sense to add anything but two vectors
            print("we don't know how to add a {} to a Vector".format(type(other)))
            raise NotImplementedError

    def __mul__(self, other):
        print("in __mul__")        
        if isinstance(other, int) or isinstance(other, float):
            # scalar multiplication changes the magnitude
            return Vector(other*self.x, other*self.y)
        else:
            print("we don't know how to multiply two Vectors")
            raise NotImplementedError

    def __matmul__(self, other):
        print("in __matmul__")
        # a dot product
        if isinstance(other, Vector):
            return self.x*other.x + self.y*other.y
        else:
            print("matrix multiplication not defined")
            raise NotImplementedError

    def __rmul__(self, other):
        print("in __rmul__")        
        return self.__mul__(other)

    def __truediv__(self, other):
        print("in __truediv__")        
        # we only know how to multiply by a scalar
        if isinstance(other, int) or isinstance(other, float):
            return Vector(self.x/other, self.y/other)

    def __abs__(self):
        print("in __abs__")        
        return math.sqrt(self.x**2 + self.y**2)

    def __neg__(self):
        print("in __neg__")        
        return Vector(-self.x, -self.y)

    def cross(self, other):
        # a vector cross product -- we return the magnitude, since it will
        # be in the z-direction, but we are only 2-d 
        return abs(self.x*other.y - self.y*other.x)

This is a basic class that provides two methods __str__ and __repr__ to show a representation of it. There was some discussion of this on slack. These two functions provide a readable version of our object.

The convection is what __str__ is human readable while __repr__ should be a form that can be used to recreate the object (e.g., via eval()). See:

http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python


In [ ]:
v = Vector(1,2)
v

In [ ]:
print(v)

Vectors have a length, and we'll use the abs() builtin to provide the magnitude. For a vector: $$ \vec{v} = \alpha \hat{i} + \beta \hat{j} $$ we have $$ |\vec{v}| = \sqrt{\alpha^2 + \beta^2} $$


In [ ]:
abs(v)

Let's look at mathematical operations on vectors now. We want to be able to add and subtract two vectors as well as multiply and divide by a scalar.


In [ ]:
u = Vector(3,5)

In [ ]:
w = u + v
print(w)

In [ ]:
u - v

It doesn't make sense to add a scalar to a vector, so we didn't implement this -- what happens?


In [ ]:
u + 2.0

Now multiplication. It makes sense to multiply by a scalar, but there are multiple ways to define multiplication of two vectors.

Note that python provides both a __mul__ and a __rmul__ function to define what happens when we multiply a vector by a quantity and what happens when we multiply something else by a vector.


In [ ]:
u*2.0

In [ ]:
2.0*u

and division: __truediv__ is the python 3 way of division /, while __floordiv__ is the old python 2 way, also enabled via //.

Dividing a scalar by a vector doesn't make sense:


In [ ]:
u/5.0

In [ ]:
5.0/u

Python 3.5 introduced a new matrix multiplication operator, @ -- we'll use this to implement a dot product between two vectors:


In [ ]:
u @ v

For a cross product, we don't have an obvious operator, so we'll use a function. For 2-d vectors, this will result in a scalar


In [ ]:
u.cross(v)

Finally, negation is a separate operation:


In [ ]:
-u

In [ ]: