A protected member is an attribute or method intended for use inside its defining class and by subclasses, but not by external callers. Python has no protected keyword or formal access restriction; a single leading underscore communicates this nonpublic intent. section 8.3 section 8.3.1
A subclass can use a protected method
class Employee: def _request_vacation(self): print("Send a vacation request.") class Supervisor(Employee): def do_something(self): self._request_vacation() Supervisor().do_something() # Send a vacation request. The single underscore signals that _request_vacation is not part of the public interface, while allowing inherited use. External code can still access it because Python does not enforce the restriction. section 8.5.4
Use the convention to make class interfaces clearer:
- Prefix an internal method or attribute with one underscore, such as _format_note or _urgency. section 8.3.1 section 8.3.6
- Keep protected helpers available to subclasses when shared implementation is expected; use a double underscore when subclasses should not access the member. section 8.5.4
- Minimize public members to improve encapsulation and keep irrelevant names out of typical autocompletion suggestions. section 8.3.1 section 8.3.5
class Task:
def __init__(self, title, desc, urgency):
self.title = title
self.desc = desc
self.urgency = urgency
self._status = "created"
self.note = ""
def complete(self, note = ""):
self.status = "completed"
self.note = self.format_note(note)
def format_note(self, note):
formatted_note = note.title()
return formatted_note
Trace the Task helper that formats notes, then apply the protected naming convention by treating it as _format_note when callers should not use it directly. section 8.3



