Search code examples
pythonoopgetter-settergetterattributeerror

I am getting an error : AttributeError: 'str' object has no attribute 'isfloat'


I am following a tuto for OOP regarding getters and setters, but I am getting an error:

AttributeError: 'str' object has no attribute 'isfloat'

@height.setter
def height(self, value):
    if value.isfloat():
        self.__height = value
    else:
        print("Please enter a number")

Does anyone know why this occurs ? Thank you in advance


Solution

  • You can use

    @height.setter
    def height(self, value):
        if isinstance(value, float): # Idea by Siva Shanmugam
            self.__height = value
        else:
            print('Please enter a number')
    

    to test if value is a float, or you simply

    @height.setter
    def height(self, value):
        self.__height = float(value)
    

    to get a TypeError if value can't convert value into float. Using this, int input and str with float character won't cause problems.