Skip to content

How to access private variable outside the class in Python | Example code

  • by

Python doesn’t have real private variables, so use the __ prefix (two underlines at the beginning make a variable) from PEP 8. Use instance _class-name__private-attribute try to access private variables outside the class in Python.

Note: There is no such thing as “Private variable or method ” in Python. Double underscore is just name mangling:

Example access a private variable outside the class in Python

Simple example code __amount is the private variable.

Outside the class, you can’t access the private variable, but inside the class, you can access the private variables.

class A:
    __amount = 45


a = A()

print(a.__amount)

Output: AttributeError: ‘A’ object has no attribute ‘__amount’

Access through method

However, inside the class, we can access the private variables. Print the value inside hello() function.

class A:
    __amount = 45

    def hello(self):
        print("Amount is ", A.__amount)


a = A()

a.hello()

Output:

How to access private variable outside the class in Python

How to prevent access to private variables outside the class in Python

Python example protected attributes.

class example:
  def __init__(self):
    self._variable1='protected variale' 
    self.__variable2='private variable'
    self.variable3='public variable'

Do comment if you have any questions or suggestions on this Python variable 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