Everything is an Object

So what objects do we know

Build-in types:


In [1]:
l = [] # List
d = {} # Dict
t = () # tuples
s = '' # strings
       # ...

File objects:


In [16]:
fobj = open('test.dat', mode='w')

Numpy arrays


In [32]:
import numpy as np

ary = np.linspace(0, 2*np.pi, 200)

Plots contain many objects


In [2]:
from matplotlib import pyplot as plt
import numpy as np

%matplotlib inline

In [3]:
fig = plt.figure(figsize=(20,5))      # Figure object

ax0 = fig.add_subplot(121)  # Axes object
ax1 = fig.add_subplot(122)  # Axes object

x = np.linspace(0, 2*np.pi, 200)
line, = ax0.plot(x, np.sin(x)) # Line1d object

x = np.linspace(0, 2*np.pi, 200)
y = np.linspace(0, 2*np.pi, 200)
img = ax1.imshow(np.random.random((10,10))) # Image object

fig.tight_layout()


But what is Object-oriented programming ?

"Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A distinguishing feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of "this" or "self"). In OO programming, computer programs are designed by making them out of objects that interact with one another".

Further features of Oo-Programming: Encapsulation, Operator Overloading, Inheritance, Polymorphism, ...


In [4]:
# Containg data
ary = np.random.random(100)

ary[0:10]


Out[4]:
array([ 0.23197965,  0.72483343,  0.80758343,  0.53450703,  0.09376497,
        0.83245363,  0.64192579,  0.92504377,  0.19259272,  0.1403496 ])

In [11]:
# Methods
ary.max() # Maximum element
ary.sum() # Sum of all elements
          # ...


Out[11]:
46.003024493142952

In [10]:
# Operators
ary + 2  # Arithmetic
ary[2]   # Indexing
ary[3:4] # Slicing
         # ...


Out[10]:
array([ 0.53450703])

How to create objects

Defining a minimum class


In [18]:
class MyObject:
    pass

Objects are instances of classes


In [19]:
a = MyObject()
b = MyObject()
c = MyObject()

a, b, c


Out[19]:
(<__main__.MyObject at 0x7d28da0>,
 <__main__.MyObject at 0x7d28eb8>,
 <__main__.MyObject at 0x7d28668>)

Building something more useful


In [20]:
import datetime

class Person:

    def __init__(self, first_name, last_name, birthday, email_address):
        self.first_name = first_name
        self.last_name = last_name
        self.birthday = birthday
        self.email_address = email_address
       
    def age(self):
        today = datetime.date.today()
        born = datetime.date(*[int(field) for field in self.birthday.split('/')])
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
      
    def email(self, message):
        print('Sending email to {} {} ({})'.format(self.first_name, self.last_name, self.email_address))   
        print(message)

In [21]:
harry = Person('Harry', 'Potter', '1980/7/31', 'harry@hogwarts.uk')

In [22]:
harry.email('Hello Harry')


Sending email to Harry Potter (harry@hogwarts.uk)
Hello Harry

In [23]:
harry.age()


Out[23]:
35

Contact Book


In [24]:
contact_book = []

contact_book.append(Person('Harry', 'Potter', '1980/7/31', 'harry@hogwarts.uk'))
contact_book.append(Person('Albert', 'Einstein', '1879/03/14', 'albert@einstein.com'))
contact_book.append(Person('Ernst', 'August', '1771/6/5', 'ernst@koeningreich_hannover.de'))
contact_book.append(Person('Karl', 'Marx', '1818/5/5', 'marx@revolution.su'))

Send some spam


In [248]:
for contact in contact_book:
    if contact.age() >= 40: 
        spam = 'You are {} years old.\nClick here to buy some blue pills.\n'.format(contact.age())
    
        contact.email(spam)


Sending email to Albert Einstein (albert@einstein.com)
You are 137 years old.
Click here to buy some blue pills.

Sending email to Ernst August (ernst@koeningreich_hannover.de)
You are 244 years old.
Click here to buy some blue pills.

Sending email to Karl Marx (marx@revolution.su)
You are 197 years old.
Click here to buy some blue pills.