Classes in Python¶

In [1]:
class Point2d:
    """Class for points in 2d"""
    def __init__(self,x,y):
        """create a point at x,y."""
        self.x = x
        self.y = y

    def translation(self,dx,dy):
        """move point by dx dy"""
        self.x += dx
        self.y += dy

    def double(self):
        """ multiple the position by two """
        self.x *= 2
        self.y *= 2

    def __str__(self):
        return "2d Point [" + str(self.x) + " , " + str(self.y) +"]" 

We can now create Point2d objects and manipulate them.

In [2]:
p1 = Point2d(2.,3.)
p1.translation(4.,0.)
print('p1 components ', p1.x, p1.y)
print('p1 = ', p1)
p1 components  6.0 3.0
p1 =  2d Point [6.0 , 3.0]
In [3]:
p2=Point2d(1.1,42)
p2.double()
print('p2 = ', p2)
p2 =  2d Point [2.2 , 84]
In [4]:
print(p1.__dict__)

print(p1.__doc__)

print(p1.translation.__doc__)
{'x': 6.0, 'y': 3.0}
Class for points in 2d
move point by dx dy
In [ ]: