Understand Python’s naming conventions for public and internal object attributes.
How It Works
A leading underscore signals a nonpublic implementation detail by convention; a double-leading-underscore name triggers class-name mangling, not true access protection. Public APIs should be documented and stable.
Security boundaries must be enforced outside of Python naming conventions.
Step-by-Step Example
class UserProfile:
def __init__(self, user_name):
self.user_name = user_name
self._cache_version = 1
self.__session_token = "temporary"
profile = UserProfile("Casey")
print(profile.user_name)
print(profile._cache_version)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Casey
1
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create a class with a public display name and one internal cache field.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Believing a leading underscore technically prevents all external access.
- Treating double underscores as an encryption or access-control mechanism.
Key Takeaways
- Understand Python’s naming conventions for public and internal object attributes.
- A leading underscore signals a nonpublic implementation detail by convention; a double-leading-underscore name triggers class-name mangling, not true access protection.
- Security boundaries must be enforced outside of Python naming conventions.