0

This "__height" and "__width" really confuse me. Could someone explain to me why these two variables are prefixed with two underscores? Will it be the same if one underscore is prefixed to these variables? What is the difference? Thanks a lot.

class Square:

    def __init__(self, height="0", width="0"):
        self.height = height
        self.width = width


    @property
    def height(self):
        return self.__height


    @height.setter
    def height(self, value):
        if value.isdigit():
            self.__height = value
        else:
            print("Please only enter numbers for height")


    @property
    def width(self):
        return self.__width


    @width.setter
    def width(self, value):
        if value.isdigit():
            self.__width = value
        else:
            print("Please only enter numbers for width")

    def getArea(self):
        return int(self.__width) * int(self.__height)


def main():
    aSquare = Square()

    height = input("Enter height : ")
    width = input("Enter width : ")

    aSquare.height = height
    aSquare.width = width

    print("Height :", aSquare.height)
    print("Width :", aSquare.width)

    print("The Area is :", aSquare.getArea())


main()

1 Answers1

-1

It's just a way to get rid of names collision, if you add two underscore at the beginning, then Python under the hood adds class name before underscore. For example in that class instead of __width it will be Square__width, and if you inherit Square and make your own width variable it won't overwrite Square__width.

vZ10
  • 2,468
  • 2
  • 23
  • 33
  • Correction: it’s [actually](https://docs.python.org/3/tutorial/classes.html#private-variables) `_Square__width`, with an additional single underscore in front. – Alex Shpilkin Jan 25 '19 at 13:52