Imagine you have a Circle class where you want the radius to always be non-negative. Which approach would you use to ensure this while still allowing direct assignment like circle.radius = 5?
- Making the radius attribute private and providing a public method to set it.
- Not allowing direct assignment to the radius attribute.
- Using a property with a setter method that checks and enforces the non-negativity of the radius.
- Using the @property decorator without a setter method.
You would use a property with a setter method to validate the radius and ensure it's non-negative while still allowing direct assignment. The setter method can perform the check.
Loading...
Related Quiz
- Which of the following set methods does not modify the set but returns a new set?
- If you're working with both CSV and JSON data formats in a project, which Python standard library module would be redundant?
- What is the primary use of the __init__ method in a Python class?
- You have a list of numbers and you want to compute the sum of all positive numbers only. Which control structure can be most beneficial to achieve this?
- You are given a list of strings. You need to create a new list that contains the length of each string in the original list. Which Python construct would be best suited for this?