Possible Error in this course : Add behavior with methods / Introduction to object-oriented programming with Python

Muhammed Gbadegesin 20 Reputation points
2025-01-05T12:58:10.84+00:00
class Square:

    def __init__(self, w, h):
        self.__height = h
        self.__width = w

    def set_side(self, new_side):
        self.__height = new_side
        self.__width = new_side

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

    @height.setter
    def height(self, new_value):
        if new_value >= 0:
            self.__height = new_value
        else:
            raise Exception("Value must be larger than 0")

In the preceding code, the function height() is decorated by the decorator @property. This decoration action creates the private field __height. The __height field isn't defined in the constructor __init__() because the decorator does that already. There's also another decoration happening, namely, @height.setter. This decoration points out a similar-looking height() method as the setter. The new height method takes on another parameter value as its second parameter.

The __height field isn't defined in the constructor __init__() because the decorator does that already.

The quoted statement mentions __height is not defined in the constructor, but it actually is. What is the correct understanding?

This question is related to the following Learning Module

Visual Studio Training
Visual Studio Training
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Training: Instruction to develop new skills.
29 questions
0 comments No comments
{count} votes

Accepted answer
  1. Q&A Assist
    2025-01-05T12:58:10.8466667+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    The quoted statement is incorrect. The __height field is indeed defined in the constructor __init__(), where it is initialized with the value of the parameter h. The @property decorator does not define the field; instead, it provides a way to access the private attribute __height through a public interface. The @height.setter decorator allows you to set the value of __height while enforcing any conditions specified in the setter method.

    In summary, the correct understanding is that the __height field is explicitly defined in the constructor, and the decorators are used to manage access to this private field.


    References:


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.