I'm new to OOP in Python and lets assume I have a class that does a simple calculation:
class Calc:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
def sum(self):
return self.n1 + self.n2
In this simplified example, what is the best way to validate the attributes of the class? For example, say if I expect a float for n1 and n2 such that I define my constructor as:
self.n1 = float(n1)
self.n2 = float(n2)
If n1 or n2 was None I would get an Attribute Error as NoneType can't be a float - for some reason, it feels 'wrong' for we to have logic in the constructor of Calc class to catch this.
Would I have some sort of validation logic before ever creating the instance of the class to catch this upstream?
Is there a way for me to use some technique to validate on the fly like perhaps decorators or property annotations?
Any advice is appreciated