Python Private Methods And Variables

Python doesn’t have private method and variable like the OOD programming language. But, we do have other way to do it.

In Python, we can use __ (double underscore) to make a method or variable private.

Private Variable

Code as below:

class Person:
def __init__(self, name, age):
self.name = name
# age is a private variable
self.__age = age
Bob = Person("Bob", 17)
print("name:", Bob.name)
# this will cause an error: no `__age` variable
print("Age:", Bob.__age)

Private Method

Code as below:

class Person:
def __init__(self, name, age):
self.name = name
# age is a private variable
self.age = age
def __agePlus(self):
self.age = self.age+1
Bob = Person("Bob", 17)
# this method will cause an error: no '__agePlus' method
Bob.__agePlus()

Access Private Stuff

Code as below:

class Person:
def __init__(self, name, age):
self.name = name
# age is a private variable
self.__age = age
Bob = Person("Bob", 17)
print("name:", Bob.name)
# this will cause an error: no `__age` variable
print("Age:", Bob.__age)
# we can access __age like this:
print(Bob._Person__age)