Reputation: 377
I have defined a class named Person with two attributes -- name and age. If age is above 40, I want to raise an exception. I am able to do this successfully within init as follows:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
if age > 40:
raise ValueError('age too high')
def get_list(self):
return [self.name, self.age]
p1 = Person('Bob', 36)
p2 = Person('John', 55)
However, in larger problems, raising all exceptions (all value or type errors, in my case) within the init statement seems cumbersome and not good programming practice, especially since more than half of the total code I would have to write would be within the initializer. So I tried:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def _verify_age(self, age):
if age > 40:
raise ValueError('age too high')
def get_list(self):
return [self.name, self.age]
p1 = Person('Bob', 36)
p2 = Person('John', 55)
But defining p2
does not raise the 'age too high' error, as before.
How can I solve this? I am still new to classes and am still trying to find the best alternative to the first block of code.
Upvotes: 1
Views: 85
Reputation: 7268
You have only defined the function, and never called it.
You can try:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self._verify_age()
def _verify_age(self):
if self.age > 40:
raise ValueError('age too high')
def get_list(self):
return [self.name, self.age]
Upvotes: 1