Private variables in Python Class: Difference of public and private attributes

Python class has public and private attributes like other languages. The name of private attribute starts with double underscores.

class Animal:

    def __init__(self, name, age):
        self.name = name
        self.__age = age


a = Animal(name='fish', age=5)

print(a.name)  # fish
print(a.__age)  # AttributeError: 'Animal' object has no attribute '__age'

name and __age are Animal class attributes (variables).

Variable Type
name public
__age private

a is an instance of Animal and name is a public attribute of a so we can access name of a. That is a.name is valid.

On the other hand, __age is private so we can't access __age of a. Python raises AttributeError due to trying to get a private attribute.

How can we get private variables?

class Animal:

    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def get_age(self):
        return self.__age


a = Animal(name='fish', age=5)

print(a.get_age())  # 5

If the class has a public function returning the private attributes, we can access them.

Python Class

Python Tutorial