What are some ways to implement conditional entries for arguments in a class?
Here is an example of what I mean, take the following class:
class Person(object):
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def get_name(self):
return self.name
def get_gender(self):
return self.gender
def get_age(self):
return self.age
In the above case, I would like an object to be created from the Person class only if the arguments for name, gender and age are of the type str
, str
and int
respectively.
In other words, if I typed:
bill = person('Bill McFoo', 'Male', '20')
The object bill
will not be created because the age was a string and not an integer.
Here is my approach; I include an if
statement in the __init__
method:
def __init__(self, name, gender, age):
self.name = name
if isinstance(age, str):
print("Age needs to be an integer you f**king idiot!")
raise ValueError
else:
self.age = age
self.gender = gender
So in the above example, the input for the argument age
is checked that it is an integer and if it is not, then it berates the user and raises an exception which prevents the object from being created. I can do the same for name
and gender
and checking that they are strings with isinstance
.
So I'm wondering if there are simpler or 'right' ways to implement argument checks like this for a class instead of the approach that I've done?