0% found this document useful (0 votes)
3 views

Access Modifiers

The document explains access modifiers in Python, detailing public, protected, and private members. Public members are accessible by default, protected members are indicated by a single underscore, and private members use name mangling with double underscores. Examples of each type are provided through class definitions and driver code.

Uploaded by

Bajrang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Access Modifiers

The document explains access modifiers in Python, detailing public, protected, and private members. Public members are accessible by default, protected members are indicated by a single underscore, and private members use name mangling with double underscores. Examples of each type are provided through class definitions and driver code.

Uploaded by

Bajrang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Access Modifiers

In Python
SANTOSH VERMA

Public Access
All member variables and methods are public by default in Python. So when you want
to make your member public, you just do nothing.

class Cup:
def __init__(self):
self.color = None
self.content = None

def fill(self, beverage):


self.content = beverage

def empty(self):
self.content = None

#Driver Code
redCup = Cup()
redCup.color = "red"
redCup.content = "tea"
redCup.empty()
Protected
 Protected member is (in C++ and Java) accessible only from within the
class and it’s subclasses. How to accomplish this in Python?

 The answer is – by convention. By prefixing the name of your member


with a single underscore,

#Driver Code
class Cup: cup = Cup()
def __init__(self): cup._content = "tea“
print(cup.color, cup._content)
self.color = None
self._content = None # protected variable

Output:
def fill(self, beverage):
None tea
self._content = beverage

def empty(self):
self._content = None
Private
 By declaring your data member private you mean, that nobody
should be able to access it from outside the class.

 Python supports a technique called name mangling. This feature


turns every member name prefixed with at least two underscores
and suffixed with at most one underscore into.

class Peak:
def _single_method(self):
pass
def __double_method(self): # for mangling
pass
class Pyth(Peak):
def __double_method(self): # for mangling
pass

You might also like