So i am working with classes and if statements. When the if statement is inside the class def, it seems to be ignored and not sure what i am doing wrong. I want it to raise an exception if the criteria is not met.
I tried to change name to __name but that did not seem to help. I also tried to remove def get_name(self) to see if that caused the problem but it did not.
class Strict:
name:str
def __init__(self,name):
self.name = name
def get_name(self):
return self.name
def set_name(self,name):
if len(name) != 5:
raise Exception("Name must be exactly 5 characters")
else:
return name
try:
z = Strict("ABCDEFGH")
print(z.name)
except Exception as e:
print(str(e))
CodePudding user response:
You never call the set_name
function inside or outside of your class. If you want to check the name on the initialization of your class, you can call that function in your __init__
function like this:
class Strict:
name:str
def __init__(self,name):
self.name = self.set_name(name)
def get_name(self):
return self.name
def set_name(self,name):
if len(name) != 5:
raise Exception("Name must be exactly 5 characters")
else:
return name
try:
z = Strict("ABCDEFGH")
print(z.name)
except Exception as e:
print(str(e))
CodePudding user response:
The pythonic way of using setters and getters is rather different. You could use the following code:
class Strict:
name:str
def __init__(self,name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self,name):
if len(name) != 5:
raise Exception("Name must be exactly 5 characters")
else:
self._name = name