Intro to types/classes/objects


In [10]:
s = 'i am a string'
type(s)


Out[10]:
str

In [11]:
type(4)


Out[11]:
int

In [12]:
type(2.5236)


Out[12]:
float

In [13]:
type([1,2,3,4,5])


Out[13]:
list

In [14]:
type({'a':4, 'b':5})


Out[14]:
dict

In [70]:
import copy

class MyObject(object):
    def __init__(self, x, y=None):
        
        self.x = x
        
        if y is not None:
            self.y = y
        
    def addme(self):
        return self.x + self.y
    
    def copy(self):
        return copy.copy(self)
    
class MyStringObject(MyObject):
    def __init__(self, x, y):
        if not (type(x)==str and type(y)==str):
            raise TypeError('you can only pass strings')
        self.x = x
        self.y = y

In [98]:
import numpy as np

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def distance_from_origin(self):
        return np.sqrt(self.x**2 + self.y**2)
    
    def __add__(self, other):
        newx = self.x + other.x
        newy = self.y + other.y
        return Point(newx, newy)

class FunInt(int):
    def __add__(self, other):
        print 'hahaha gotcha---sucker!'
        return self.real - other.real

In [101]:
x = FunInt(4)
y = FunInt(7)

In [102]:
x + y


hahaha gotcha---sucker!
Out[102]:
-3

In [89]:
p1 = Point(3,4)
p2 = Point(5,6)

In [90]:
p3 = p1 + p2


i am a pumpkin!

In [85]:
p3.x, p3.y


Out[85]:
(8, 10)

In [87]:
type(2 + 2)


Out[87]:
int

In [ ]:


In [ ]:


In [71]:
objs = MyStringObject('a','b')

In [72]:
objs.addme()


Out[72]:
'ab'

In [ ]:


In [64]:
obj = MyObject(6)
print obj.y


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-64-70bd13ac7189> in <module>()
      1 obj = MyObject(6)
----> 2 print obj.y

AttributeError: 'MyObject' object has no attribute 'y'

In [59]:
obj = MyObject(5,6)
obj2 = MyObject(7,8)

In [60]:
copyobj = obj.copy()

In [61]:
copyobj.x = 1230

In [62]:
print copyobj.x
print obj.x


1230
5

In [45]:
import numpy as np

x = np.arange(10)
print x


[0 1 2 3 4 5 6 7 8 9]

In [46]:
y = x.copy()
y[4] = 1000
print x


[0 1 2 3 4 5 6 7 8 9]

In [30]:
obj.x, obj.y


Out[30]:
(5, 6)

In [31]:
obj.addme()


Out[31]:
11

In [21]:
obj2.x


Out[21]:
7

In [22]:
d = dict(r=4, x=7)

In [23]:
type(d)


Out[23]:
dict

In [24]:
'please split me'.split()


Out[24]:
['please', 'split', 'me']

In [ ]: