How to Protect Python Class Attributes with Private Variables: A Hands‑On Guide
This article explains how Python class attributes can be hidden from external code using double‑underscore name mangling, demonstrates the effect with concrete examples, and shows how to provide controlled access through getter, setter, and validation methods.
1. Introduction
In a class, attributes and methods can be defined, and external code can manipulate data by calling instance methods, which hides internal complexity.
2. Case Analysis
Consider a Teacher class where external code can freely modify name and score attributes.
class Teacher(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
bart = Teacher('Bart Simpson', 98)
lisa = Teacher('Lisa Simpson', 87)
bart.score = 59
print(bart.score)
print('bart.score =', bart.score)Running the code produces the expected output (shown in the image below).
To prevent external access, prefix attribute names with double underscores, making them private.
class Teacher(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))After this change, external code cannot directly access __name or __score:
bart = Teacher('Bart Simpson', 98)
print(bart.__name) # AttributeErrorTo still allow reading these values, add getter methods:
class Teacher(object):
def get_name(self):
return self.__name
def get_score(self):
return self.__scoreIf external code should also modify score, provide a setter with validation:
class Teacher(object):
def set_score(self, score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')Using a setter lets you check parameters before changing the internal state, making the code more robust.
Note that names beginning and ending with double underscores (e.g., __init__) are special methods and are not private. Single‑underscore names (e.g., _name) are merely a convention for “protected” attributes and can still be accessed.
Python performs name mangling for double‑underscore attributes, internally renaming __name to _Teacher__name. This means you can still access the variable using the mangled name:
print(bart._Teacher__name)Although the mangled name can be accessed, it should be treated as private and not used directly.
3. Conclusion
This article, based on basic Python knowledge, introduced attribute access restrictions in classes. Through practical examples, it highlighted important points, common pitfalls, and effective solutions for encapsulation.
Experiment with the code yourself; hands‑on practice deepens understanding.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
