I have a design issue in Python, but I'm not very advanced neither in the language, nor in design, nor in Exceptions.
Here is what I want: I have a class with attributes like name, budget, ... and I want to be impossible to create object with lets say name shorter than 3 symbols and budget < 0. Also I want when changing some of this values, they to be checked again. If you try to create an object which doesn't meet this conditions, I want exception to be thrown.
Here is what I tried:
def __init__(self, name, budget):
try:
self.set_name(name)
self.set_budget(budget)
except Exception as e:
print(e)
return None
def set_name(name):
if len(name) < 3:
raise Exception("short name")
else:
self.__name = name
But here I have two problems :( The first one is that even when I try to create object with the name 'a' for example it IS created :( and I don't want invalid objects to be created. The second problem is that I have print in my init method and I don't want to have any I/O functions in it. But then how to get the message? How to get from the constructor what is the reason for not creating the object?
Also, this is for a very simple task and I don't want to overdo it with sophisticated and too long and hard solution :(
Can you please help me? Thank you very much in advance! :)