17. Public, Protected and Private in Python Classes (Video in Khmer)
Learn public, protected, and private attributes in Python classes with simple examples and tips for beginners.
2026-10-25 ยท 3 min read
Hello friend! ๐ Python use naming rules for public, protected, and private class data. They help show how you should use an attribute.
Important: Python does not fully block access to these attributes. The names show how you should use them.
๐ Public Attribute
Public attribute can be used inside and outside the class. Use a normal name.
class Student:
def __init__(self, name):
self.name = name
student = Student("Dara")
print(student.name) # Dara
name is public. You can read or change it outside the class.
๐ก๏ธ Protected Attribute
Start the name with one underscore _. This means: use it inside the class, or in a child class. It is a Python convention, not a strict rule.
class Student:
def __init__(self, name):
self._name = name
def show_name(self):
print(self._name)
student = Student("Dara")
student.show_name() # Dara
_name can still be accessed outside the class, but it is better not to do that.
๐ Private Attribute
Start the name with two underscores __. Python changes the name inside the class to help avoid accidental access or name conflicts.
class Student:
def __init__(self, score):
self.__score = score
def get_score(self):
return self.__score
student = Student(95)
print(student.get_score()) # 95
Use a method like get_score() to read the private attribute.
Python does not make it truly private. The double underscore is not a security feature.
๐ซ Example: Manage a Classroom
Keep the student list in a class and use methods to add and show students.
class Classroom:
def __init__(self):
self.__students = []
def add_student(self, name):
self.__students.append(name)
def show_students(self):
for student in self.__students:
print(student)
room = Classroom()
room.add_student("Dara")
room.add_student("Mina")
room.show_students()
Output:
Dara
Mina
๐ฅ Video: Example Manage Classroom with List of Students (Khmer)
๐ฅ Video: Using Private, Protected and Public in a Class (Khmer)
๐ Quick Table
| Name style | Example | Meaning |
|---|---|---|
| Public | name | Use it anywhere |
| Protected | _name | Internal use by convention |
| Private | __name | Python changes the name to avoid accidental access |
๐ก Tips
- Use public names for data that is okay to access directly.
- One underscore
_namemeans internal use by convention. - Two underscores
__namehelp avoid accidental access and name conflicts. - Use methods when you want to control how data is read or changed.
- Python naming conventions do not provide security or fully block access.
- Use clear names so your code is easy to understand.
โ Any Question?
Tell us in comment below! ๐
#Python #Class #Public #Private #Encapsulation #LearnPython #Beginner