Start learning free

LESSON 630 OF 673 · OBJECT-ORIENTED PROGRAMMING

Access in Python (by convention)

Lesson

TL ; DR:

  • Python has no public / private keywords. Privacy is signalled by naming convention:

    • name — public, anyone can read/write.
    • _name — "internal", treat as private (the underscore is a hint to other programmers).
    • __name — name-mangled to _ClassName__name to avoid subclass collisions.

  • Nothing actually stops outside code from reading obj._name. The convention is enforced socially, not by the runtime.



Full lesson:

In Java/C#/C++, the language stops you from reading a private field. In Python, the philosophy is "we're all consenting adults" — the language assumes you read the docs and respect the prefix.


The convention

class Dog:
    def __init__(self, name):
        self._name = name      # "private by convention"

    def get_name(self):
        return self._name

Outside code could still write rex._name, but it shouldn't — the underscore signals "internal, may change without notice".


Your task

The Dog constructor stores the name as self._name. Add a get_name(self) method that returns it.

Dog's name: Rex
STEP 1 OF 2
    Ctrl + Enter to check