Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

6. Use @property Decorator To Control Attributes Precisely

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • Property decorators
  • validate property must be relate to other property classvalidator

  • 6. Use @property Decorator To Control Attributes Precisely

    0

    In Python, you can access and modify the attributes of an object directly, using dot notation.

    However, it is generally a good object-oriented programming practice to access and modify the attributes of an object through their getters, setters, and deleters, rather than directly using dot notation. This is because using getters, setters, and deleters can give you more control over how the attributes are accessed and modified, and can make your code more readable and easier to understand.

    For example, the following example defines a setter method for the attribute _score to limit the range of its value:

    works as expected. However, the above implementation seems not elegant enough.

    It would be better if we can modify the attribute like a normal attribute using dot notation but still has the limitations, rather than having to call the setter method like a function.

    This is why Python provides a built-in decorator named @propery. Using it, we can modify attributes using dot notation directly. It will improve the readability and elegance of our code.

    Now, let’s change the previous program a bit:

    Popularity 1/10 Helpfulness 1/10 Language python
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 13 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.