Fundamentals 9 min read

Master Python Encapsulation & Inheritance: Public vs Private Variables Explained

This article explains Python's object-oriented principles, illustrating how encapsulation hides data through public and private instance variables, demonstrates getter/setter methods, and shows inheritance by extending classes, all accompanied by clear code examples.

21CTO
21CTO
21CTO
Master Python Encapsulation & Inheritance: Public vs Private Variables Explained

Encapsulation: Hiding Information

Encapsulation in object-oriented programming restricts direct access to an object’s data and methods, allowing the internal representation to be hidden from the outside.

Public Instance Variables

In Python a public instance variable can be created in the constructor:

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

raymond = Person('Raymond')
print(raymond.first_name)  # => Raymond

A class attribute can also be defined directly in the class body:

class Person:
    first_name = 'Raymond'

ex = Person()
print(ex.first_name)  # => Raymond

Public variables can be reassigned simply by assigning a new value:

ex = Person('Raymond')
ex.first_name = 'Jason'
print(ex.first_name)  # => Jason

Non-Public Instance Variables

Python has no true private attributes, but a leading underscore is the convention for non-public members.

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

ex = Person('raymond', '[email protected]')
print(ex._email)  # => [email protected]

Typical getter and setter methods are used to access and modify such attributes:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

    def email(self):
        return self._email

    def update_email(self, new_email):
        self._email = new_email

ex = Person('raymond', '[email protected]')
print(ex.email())          # => [email protected]
ex.update_email('[email protected]')
print(ex.email())          # => [email protected]

Public Methods

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._age

raymond = Person('Raymond', 38)
print(raymond.show_age())  # => 38

Non-Public Methods

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def _show_age(self):
        return self._age

raymond = Person('Raymond', 38)
print(raymond._show_age())  # => 38

Another pattern uses a public method that calls a non-public helper:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._get_age()

    def _get_age(self):
        return self._age

raymond = Person('Raymond', 38)
print(raymond.show_age())  # => 38

Inheritance: Sharing Behavior and Features

Classes can inherit attributes and methods from a parent class.

class Car:
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)      # => 4
print(my_car.seating_capacity)      # => 5
print(my_car.maximum_velocity)     # => 250

A subclass can reuse the parent’s implementation without redefining it:

class ElectricCar(Car):
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels)      # => 4
print(my_electric_car.seating_capacity)      # => 5
print(my_electric_car.maximum_velocity)     # => 250

Summary

How Python variables work

How conditional statements work

How loops work

Using lists and sorting

Dictionary key-value structures

Iterating over data structures

Objects and classes

Attributes as object data

Methods as object behavior

Setting and getting attributes in Python

Encapsulation: hiding information

Inheritance: sharing behavior and features

Congratulations on completing this intensive Python basics series.

More advanced Python content will be released soon.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

OOPEncapsulationInheritanceprivate variablesPublic Variables
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.