Recall & Review
beginner
What is the purpose of the
@property decorator in Python?The
@property decorator allows you to define a method that can be accessed like an attribute. It helps to control access to instance variables while keeping the syntax simple and clean.Click to reveal answer
intermediate
How do you define a setter method for a property in Python?
You define a setter method by using the
@property_name.setter decorator above a method with the same name as the property. This method allows you to set the value while controlling or validating it.Click to reveal answer
beginner
What happens if you try to set a value to a property without defining a setter?
If no setter is defined, trying to assign a value to the property will raise an
AttributeError. This protects the property from being changed directly.Click to reveal answer
beginner
Explain the difference between a regular method and a property method in Python.
A regular method requires parentheses to be called (e.g.,
obj.method()), while a property method can be accessed like an attribute without parentheses (e.g., obj.property). Properties provide a way to use methods as if they were attributes.Click to reveal answer
beginner
Show a simple example of a class with a property and a setter using the <code>@property</code> decorator.Example:<br><pre>class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if not value:
raise ValueError('Name cannot be empty')
self._name = value
p = Person('Alice')
print(p.name) # Outputs: Alice
p.name = 'Bob' # Sets new name
</pre>Click to reveal answer
What does the
@property decorator do in Python?✗ Incorrect
The
@property decorator makes a method behave like a read-only attribute.How do you define a setter for a property named
age?✗ Incorrect
The setter for a property
age is defined with @age.setter.What error occurs if you try to set a property without a setter?
✗ Incorrect
Trying to set a property without a setter raises an
AttributeError.Which of these is a benefit of using properties?
✗ Incorrect
Properties let you control attribute access while keeping syntax clean.
How do you access a property method in Python?
✗ Incorrect
Property methods are accessed like attributes, without parentheses.
Explain how the
@property decorator works and why it is useful.Think about how you can hide internal details but still let users get or set values easily.
You got /4 concepts.
Describe how to create a property with both getter and setter methods in a Python class.
Remember the setter decorator uses the property name.
You got /4 concepts.