So I have read a lot about property keyword and I believe I have gotten the gist of it. I came across this example
class PeopleHeight:
def __init__(self, height = 150):
self.height = height
def convert_to_inches(self):
return (self.height * 0.3937)
def get_height(self):
print("Inside the getter method")
return self._height
def set_height(self, value):
if value < 0:
raise ValueError("Height cannot be negative")
print("Inside the setter method")
self._height = value
height = property(get_height, set_height) #---->CONFUSING
and the last statement which is confusing me
height = property(get_height, set_height)
I understand that the property statement has the signature
property(fget=None, fset=None, fdel=None, doc=None)
What I dont get is get_height and set_height. I understand that height is a class variable (not an instance variable) but what about get_height and set_height.I am thinking that above should have been
height = property(get_height, set_height)
but thats wrong syntax as there is no self.My question is why dont we get an error when we say:
property(get_height, set_height)
as there are no definitions of get_height or set_height set as class scope.
get_heightandset_heightare set in class scope. All functions in theclassbody are class-scope objects.selfare instance attributes. Methods receive the instance as the first argument, commonly namedself, but that's not really a scope as Python understands it.@propertydecorator too.