Straightforward programming:
def add_two_numbers(a, b):
return a + b
print(add_two_numbers(4, 5)) #prints 9
Modern programming:
def print_error():
print("Error: Operation string does not match operation object. Looks like you don't understand how our library works.")
class Operation:
def get_a(self):
print("This function must be overridden")
def get_b(self):
print("This function must be overridden")
def __init__(self, typeStr):
if self.type != typeStr:
print_error()
self.type = typeStr
def perform_operation(self):
if self.type == "+":
return self.get_a() + self.get_b()
if self.type == "-":
return self.get_a() - self.get_b()
class Add(Operation):
def get_a(self):
return self.a
def get_b(self):
return self.b
def __init__(self, a, b, typeStr):
self.type = typeStr
super().__init__(typeStr)
self.a = a
self.b = b
class Subtract(Operation):
def get_a(self):
return self.a
def get_b(self):
return self.b
def __init__(self, a, b, typeStr):
self.type = typeStr
super().__init__(typeStr)
self.type = "-"
self.a = a
self.b = b
def operation(a, b, operation, operationObject):
if operation != operationObject.type:
print_error()
return
if type(operationObject) == Add:
value = operationObject.perform_operation()
verification = Subtract(value, b, "-").perform_operation()
if verification != a:
print("There was an error verifying the result")
return value
def add_two_numbers(a, b):
operationObject = Add(a, b, "+")
return operation(a, b, "+", operationObject)
print(add_two_numbers(4, 5)) #prints 9
[–][deleted] 2 insightful - 1 fun2 insightful - 0 fun3 insightful - 0 fun3 insightful - 1 fun - (1 child)
[–]bobbobbybob 2 insightful - 1 fun2 insightful - 0 fun3 insightful - 0 fun3 insightful - 1 fun - (0 children)
[–]filbs111 2 insightful - 1 fun2 insightful - 0 fun3 insightful - 0 fun3 insightful - 1 fun - (0 children)