Closed aj3sh closed 1 year ago
Basic POC.
>>> class nepalinumber(float):
... pass
...
>>>
>>> a = nepalinumber(1)
>>> 1 + a
2.0
>>> a + 1
2.0
>>> a / 2
0.5
>>> str(a)
'1.0'
>>> a == 1
True
>>> a > 2
False
>>> a <= 1
True
cc: @sugat009, @ecedreamer
from typing import Optional, TypeVar
selfnepalinumber = TypeVar("selfnepalinumber", bound="nepalinumber")
class nepalinumber: def init(self, value) -> None: self.value = value
def __str__(self) -> str:
return str(self.value)
def __int__(self) -> int:
return int(self.value)
def __float__(self) -> float:
return float(self.value)
def __add(self, other) -> Optional[selfnepalinumber]:
if (
(isinstance(self.value, int) and isinstance(other, int))
or (isinstance(self.value, int) and isinstance(other, float))
or (isinstance(self.value, float) and isinstance(other, int))
or (isinstance(self.value, float) and isinstance(other, float))
):
val = self.value + other
return nepalinumber(val)
elif isinstance(other, nepalinumber):
val = self.value + other.value
return nepalinumber(val)
return None
def __add__(self, other) -> selfnepalinumber:
added_value = self.__add(other)
if added_value:
return added_value
raise Exception(
f'Operator "+" not supported for types nepalinumber and "{type(object)}'
)
def __radd__(self, other) -> selfnepalinumber:
added_value = self.__add(other)
if added_value:
return added_value
raise Exception(
f'Operator "+" not supported for types "{type(object)} and nepalinumber'
)
if name == "main": num = nepalinumber(10) print(float(num))
num2 = nepalinumber(1.1)
print(int(num2))
num3 = 69
num4 = 20
print(num + num3)
print(num + num2)
print(num4 + num)
print(num4 + num2)
print(num + num2)
@sugat009, Yours looks good to me. Let's discuss about the extra features/test cases if any and start the development.
Let's create
nepalinumber
class which will be compatible with python'sint
,float
, etc numbers. The major features will be comparison, addition, subtraction, multiplication, and division. A lot of features can be added later.Here are some basic example of this class