Ad Code

Use operator overloading to accept int and float values from the user and perform addition ,subtraction using inbuilt special functions __add__() etc.

Use operator overloading to accept int and float values from the user and perform addition ,subtraction using inbuilt special functions __add__() etc.

Code:

class CustomNumber:

    def __init__(self, value):

        self.value = value


    def __add__(self, other):

        if isinstance(other, (int, float)):

            return self.value + other

        elif isinstance(other, CustomNumber):

            return self.value + other.value

        else:

            raise TypeError("Unsupported operand type(s) for +: 'CustomNumber' and '{}'".format(type(other)))


    def __sub__(self, other):

        if isinstance(other, (int, float)):

            return self.value - other

        elif isinstance(other, CustomNumber):

            return self.value - other.value

        else:

            raise TypeError("Unsupported operand type(s) for -: 'CustomNumber' and '{}'".format(type(other)))


# Example usage

if __name__ == "__main__":

    # Create instances of CustomNumber with int and float values

    num1 = CustomNumber(5)

    num2 = CustomNumber(3.5)


    # Perform addition using operator overloading

    result_add_int = num1 + 10

    result_add_float = num2 + 2.5

    result_add_custom = num1 + num2


    # Perform subtraction using operator overloading

    result_sub_int = num1 - 2

    result_sub_float = num2 - 1.5

    result_sub_custom = num1 - num2


    # Print results

    print("Addition Results:")

    print("Integer + Integer:", result_add_int)

    print("Float + Float:", result_add_float)

    print("CustomNumber + CustomNumber:", result_add_custom)

    print("\nSubtraction Results:")

    print("Integer - Integer:", result_sub_int)

    print("Float - Float:", result_sub_float)

    print("CustomNumber - CustomNumber:", result_sub_custom)


Reactions

Post a Comment

0 Comments