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.
class Sample:
def __init__(self, n1, n2):
self.n1=n1
self.__n2=n2
def display(self):
print("Class variable 1 =
", self.n1)
print("Class variable 2 =
", self.__n2)
S=Sample(12, 14)
S.display()
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.
Output
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
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.