0% found this document useful (0 votes)
5 views2 pages

Class Notes For Python Encapsulation

Encapsulation in Python protects class data by keeping properties and methods together while controlling access. Private properties can be created using a double underscore prefix, preventing direct access from outside the class. Getter and setter methods allow for controlled access and modification of private properties.

Uploaded by

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

Class Notes For Python Encapsulation

Encapsulation in Python protects class data by keeping properties and methods together while controlling access. Private properties can be created using a double underscore prefix, preventing direct access from outside the class. Getter and setter methods allow for controlled access and modification of private properties.

Uploaded by

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

Python Encapsulation

Encapsulation is about protecting data inside a class.


It means keeping data (properties) and methods together in a class, while controlling
how the data can be accessed from outside the class.
This prevents accidental changes to your data and hides the internal details of how your
class works.

Private Properties
In Python, you can make properties private by using a double underscore __ prefix:
ExampleGet your own Python Server
Create a private class property named __age:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age # Private property

p1 = Person("Emil", 25)
print([Link])
print(p1.__age) # This will cause an error
Note: Private properties cannot be accessed directly from outside the class.

Get Private Property Value


To access a private property, you can create a getter method:
Example
Use a getter method to access a private property:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age

def get_age(self):
return self.__age

p1 = Person("Tobias", 25)
print(p1.get_age())

Set Private Property Value


To modify a private property, you can create a setter method.
The setter method can also validate the value before setting it:
Example
Use a setter method to change a private property:
class Person:
def __init__(self, name, age):
[Link] = name
self.__age = age

def get_age(self):
return self.__age

def set_age(self, age):


if age > 0:
self.__age = age
else:
print("Age must be positive")

p1 = Person("Tobias", 25)
print(p1.get_age())

p1.set_age(26)
print(p1.get_age())

You might also like