Skip to content

Private members in Python | Example code

  • by

Python doesn’t have any mechanism that effectively restricts access to Private Members like instance variables or methods. Using prefix single or double underscore in a method or variable name to emulate the behavior of protected and private access specifiers.

Example Private members in Python

Simple example code to make private members. Using a double underscore __ prefixed to a variable makes it private. It can’t access outside the class.

class Student:
    __schoolName = 'XYZ School'  # private class attribute

    def __init__(self, name, age):
        self.__name = name  # private instance attribute
        self.__salary = age  # private instance attribute

    def __display(self):  # private method
        print('This is private method.')

std = Student("Bill", 25)


Private members in Python

Access private members in Child class example

class Human():
    # Private var
    __privateVar = "this is __private variable"

    # Constructor method
    def __init__(self):
        self.className = "Human class constructor"
        self.__privateVar = "this is redefined __private variable"

    # Public method
    def showName(self, name): = name
        return self.__privateVar + " " + name

    # Private method
    def __privateMethod(self):
        return "Private method"

    # Public method that returns a private variable
    def showPrivate(self):
        return self.__privateMethod()

    def showProtecded(self):
        return self._protectedMethod()

class Male(Human):
    def showClassName(self):
        return "Male"

    def showPrivate(self):
        return self.__privateMethod()

    def showProtected(self):
        return self._protectedMethod()

class Female(Human):
    def showClassName(self):
        return "Female"

    def showPrivate(self):
        return self.__privateMethod()

human = Human()

male = Male()

female = Female()


Human class constructor
this is redefined __private variable Vasya
Private method
Human class constructor
Human class constructor

Do comment if you have any doubts or suggestions on this Python access control tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *