Bird
0
0

You want to create a class Student with a public attribute grade that can be updated anytime. Which code correctly implements this?

hard📝 Application Q8 of 15
Python - Encapsulation and Data Protection
You want to create a class Student with a public attribute grade that can be updated anytime. Which code correctly implements this?
Aclass Student(): def __init__(self, grade): self.grade = grade s = Student('A') s.grade = 'B' print(s.grade)
Bclass Student(): def __init__(self, grade): self._grade = grade s = Student('A') s._grade = 'B' print(s._grade)
Cclass Student(): def __init__(self, grade): grade = self.grade s = Student('A') s.grade = 'B' print(s.grade)
Dclass Student(): def __init__(self, grade): self.__grade = grade s = Student('A') s.__grade = 'B' print(s.__grade)
Step-by-Step Solution
Solution:
  1. Step 1: Check attribute assignment for public access

    class Student(): def __init__(self, grade): self.grade = grade s = Student('A') s.grade = 'B' print(s.grade) assigns grade as a public attribute with no underscores.
  2. Step 2: Confirm attribute can be updated and accessed

    class Student(): def __init__(self, grade): self.grade = grade s = Student('A') s.grade = 'B' print(s.grade) updates s.grade and prints it correctly.
  3. Final Answer:

    The code using self.grade = grade without underscores correctly implements public attribute update and access. -> Option A
  4. Quick Check:

    Public attribute = self.attribute, modifiable anytime [OK]
Quick Trick: Public attributes have no underscores and can be changed anytime [OK]
Common Mistakes:
  • Using underscores for public attributes
  • Reversing assignment order
  • Trying to access private attributes directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes