0

why is my setter not working

I tried to check if an input is even or not in this code but it is not giving me False for odd numbers. Any idea why my code is not working? class Number: def __init__(self, num): self.value = num self._iseven = True @property def iseven(self): return self._iseven @iseven.setter def iseven(self, value): if value%2==0: self._iseven = True return self._iseven else: return False x = Number(int(input())) print(x.iseven) https://code.sololearn.com/csaoLYEmGt5A/?ref=app

22nd Aug 2021, 2:07 PM
Zechariah YAKAP
Zechariah YAKAP - avatar
5 ответов
+ 5
Can't really understand the logic in your iseven setter. A number can only be even or not, why check for other condition. This 👇should solve your problem https://code.sololearn.com/cX2K1Vu5HdxM/?ref=app
22nd Aug 2021, 2:50 PM
Baribor Saturday
Baribor Saturday - avatar
+ 2
Zechariah YAKAP if you reverse the order, self.__ieven will be evaluated last setting it to None. Actually the code will still work perfectly if you comment out self.__iseven = None. Try it and see. (In python, creating a class property is not only limited to the __init__ method
22nd Aug 2021, 7:18 PM
Baribor Saturday
Baribor Saturday - avatar
+ 1
✔✅Barry🔧 Thank for answering, You are right, the elif was unnecessary but what I Dont understand is, my setter conditions were not picking up, the difference I realize is: in your fix house have set iseven = num, while I set it to 'value' which I was using to check condition, any reasons why going have set it to iseven? honestly I still don't understand why my code did not work I also realized that the order, self.__iseven= None self.iseven = num #works self.iseven = num self.__iseven= None #Outputs None for every case, Why is the order important? apologies if this sounds silly , I'm new to Python
22nd Aug 2021, 5:04 PM
Zechariah YAKAP
Zechariah YAKAP - avatar
+ 1
SoloProg your code is straight forward, it raises an AttributeError: Can not set attribute if we do this: y = Number(24) y.iseven = False this may not be a classic example but the whole point of setters is to avoid directly altering attributes which is why a property setter is used. https://code.sololearn.com/cqF8EQGoqXMD/?ref=app
22nd Aug 2021, 5:13 PM
Zechariah YAKAP
Zechariah YAKAP - avatar
0
✔✅Barry🔧 thank you, tried it and it worked without that line too
24th Aug 2021, 8:56 PM
Zechariah YAKAP
Zechariah YAKAP - avatar