I’m learning python. I’d like for self.characteristic to be set to 5 when an object of the class is created. I’m using the set.characteristic method, because in reality there would be a bunch of calculations to reach the value 5. I’d expect the output of my code below to be 5, but I get None. Why? Thanks!
class AnyClass:
def __init__(self):
self.characteristic = self.set_characteristic()
def set_characteristic(self):
# in reality would do a bunch of calculations
self.characteristic = 5
obj = AnyClass()
print(obj.characteristic)
# Output: None
# Expected output: 5
>Solution :
You forgot to return the desired value in your function.
def set_characteristic(self):
# in reality would do a bunch of calculations
return 5
When you do not return a value, function returns None.