Object Oriented Programming (OOP)¶
In [26]:
class Point2d():
def __init__(self, x, y, u = 'meter'):
self.x= x
self.y = y
self.__unit = u
def get_units(self):
print(self.__unit)
def set_units(self, u):
if u.lower() in ['meter', 'inches', 'milimiters', 'centimiters']:
self.__unit = u
else:
print("{} ins not a valid unit".format(u))
def distance_xy(self, p2d, rnd = None):
dist = ((self.x - p2d.x)**2 + (self.y - p2d.y)**2 )**.5
if rnd:
dist = round(dist, rnd)
return dist
def __repr__(self):
return 'Point Coord \nx: {}\ny: {}\nUnit: {}'.format(self.x, self.y, self.__unit)
In [27]:
p2d_1 = Point2d(3,4.3)
p2d_2 = Point2d(5, 7)
In [28]:
d1 = p2d_1.distance_xy(p2d_2,5)
d1
Out[28]:
3.36006
In [29]:
d1 = p2d_1.distance_xy(p2d_2)
d1
Out[29]:
3.3600595232822887
In [30]:
print(p2d_1)
Point Coord x: 3 y: 4.3 Unit: meter
In [31]:
p2d_1.get_units()
meter
Inheritance¶
In [32]:
class Point3d(Point2d):
def __init__(self, x, y, z, u='meters'):
Point2d.__init__(self, x, y , u)
self.z= z
def distance_xyz(self, p2d, rnd = None):
dist = ((self.x - p2d.x)**2 + (self.y - p2d.y)**2 + (self.z - p2d.z)**2 )**.5
if rnd:
dist = round(dist, rnd)
return dist
def __repr__(self):
return 'Point Coord \nx: {}\ny: {}\nz: {}\nUnit: {}'.format(self.x, self.y, self.z, self.__unit)
In [33]:
p3d_1 = Point3d(3,4.3,0)
p3d_2 = Point3d(5, 7,7)
In [34]:
p3d_1.distance_xy(p3d_2)
Out[34]:
3.3600595232822887
In [35]:
p3d_1.distance_xyz(p3d_2)
Out[35]:
7.764663547121665