52 lines
1.1 KiB
Python
52 lines
1.1 KiB
Python
|
import numpy as np
|
||
|
|
||
|
class Ball:
|
||
|
__diameter__ = 0.0
|
||
|
|
||
|
## Methods
|
||
|
# Constructor
|
||
|
def __init__(self, diameter = 1.0):
|
||
|
self.__diameter__ = diameter
|
||
|
pass
|
||
|
|
||
|
# a simple method
|
||
|
def introduction(self):
|
||
|
print(f"My diameter is {self.__diameter__:.3f}.")
|
||
|
pass
|
||
|
|
||
|
# Getter
|
||
|
def get_diameter(self):
|
||
|
return self.__diameter__
|
||
|
|
||
|
# overload __add_ (+)
|
||
|
def __add__(self, other):
|
||
|
d1 = self.get_diameter()
|
||
|
|
||
|
if(isinstance(other, Ball)):
|
||
|
d2 = other.get_diameter()
|
||
|
combined_volume = 1/6 * np.pi * (d1**3 + d2**3)
|
||
|
elif(isinstance(other, int) or isinstance(other, float)):
|
||
|
combined_volume = 1/6 * np.pi*d1**3 + other
|
||
|
else:
|
||
|
raise ValueError("Invalid summand.")
|
||
|
d_combined = np.power(6 * combined_volume / np.pi, 1/3)
|
||
|
return Ball(d_combined)
|
||
|
|
||
|
# overload __radd__ (number + Ball)
|
||
|
def __radd__(self, other):
|
||
|
return self + other
|
||
|
|
||
|
# main code
|
||
|
a = Ball()
|
||
|
b = Ball(2.0)
|
||
|
|
||
|
c = a + b
|
||
|
|
||
|
d = a + 5
|
||
|
e = 5 + a
|
||
|
|
||
|
a.introduction()
|
||
|
b.introduction()
|
||
|
c.introduction()
|
||
|
d.introduction()
|