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)
std.__schoolName

Output:

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):
        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()
print(human.className)
print(human.showName("Vasya"))
print(human.showPrivate())

male = Male()
print(male.className)
print(male.showClassName())

female = Female()
print(female.className)
print(female.showClassName())

Output:

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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading