POO


In [1]:
class Point(object):
    pass

# class Point:
#     pass

In [5]:


In [ ]:
p = Point()

In [6]:
p.x = 10
p.y = 10

In [7]:
p.x


Out[7]:
10

In [8]:
p.y


Out[8]:
10

In [12]:
class Point(object):
    x = 10
    y = 10

In [13]:
p = Point()

In [14]:
p.x


Out[14]:
10

In [15]:
Point.x


Out[15]:
10

In [16]:
Point.y


Out[16]:
10

In [17]:
p.x = 20

In [18]:
p.x


Out[18]:
20

In [19]:
Point.x


Out[19]:
10

In [29]:
class Point(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

In [30]:
p = Point(10)

In [31]:
p.x


Out[31]:
10

In [32]:
p = Point(1, 1)

In [33]:
p.y


Out[33]:
1

In [34]:
import math
class Point(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def distance(self, other_point):
        return math.sqrt(
            (self.x + other_point.x) ** 2 + (self.y + other_point.y) ** 2
        )

In [35]:
p1 = Point(1, 1)
p2 = Point(4, 5)

In [36]:
p1.distance(p2)


Out[36]:
7.810249675906654

In [37]:
Point.distance(p1, p2)


Out[37]:
7.810249675906654

In [38]:
p2.distance(p1)


Out[38]:
7.810249675906654

In [39]:
p1 + p2


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-a4b876bf3cd8> in <module>()
----> 1 p1 + p2

TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

In [47]:
class Point(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __str__(self):
        return 'X: %s, Y: %s' % (self.x, self.y)
    def __repr__(self):
        return '<Point %s>' % str(self)

In [48]:
p1 = Point(1, 1)
p2 = Point(4, 3)

In [49]:
p1 + p2


Out[49]:
<Point X: 5, Y: 4>

In [ ]: