![if !IE]> <![endif]>
Public and Private Data Members
The variables which are defined inside the class is public by default. These variables can be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables can be accessed only within the class.
def __init__(self, n1, n2):
print("Class variable 1 = ", self.n1)
print("Class variable 2 = ", self.__n2)
print("Value 1 = ", S.n1)
print("Value 2 = ", S.__n2)
In the above program, there are two class variables n1 and n2 are declared. The variable n1 is a public variable and n2 is a private variable. The display( ) member method is defined to show the values passed to these two variables.
The print statements defined within class will successfully display the values of n1 and n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method defined inside the class. But, when we try to access the value of n2 from outside the class Python throws an error. Because, private variable cannot be accessed from outside the class.
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Traceback (most recent call last):
File "D:/Python/Class-Test-04.py", line 12, in <module> print("Value 2 = ", S.__n2)
AttributeError: 'Sample' object has no attribute '__n2
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.