Maintaining Privacy in a Public World
Intuitive Python — by David Muller (37 / 41)
👈 Installing Third-Party Packages Securely with pip | TOC | Keeping Your Source Organized 👉
Sometimes Python can feel like a bit of the wild wild west — this can feel especially true for programmers coming from a language like Java where variables and classes can be explicitly scoped as public, private, protected, and so on. In this section, you’ll learn more about how variable privacy works in Python so you better understand how to protect your programs from unexpected manipulation.
Finding No Privacy in Python
Python programs do not support truly private variables, methods, or functions. Anything you define in a Python file can be discovered and potentially mangled by other parts of your program.
Let’s consider an example class representing a dinosaur egg that can hatch:
class DinosaurEgg:
def __init__(self, egg_id):
self.egg_id = egg_id
self.hatch_status = None
def hatch(self):
if self.hatch_status is not None:
raise ValueError(f"Egg {self.egg_id} has already been hatched.")
self.hatch_status = "hatched"
print(f"Egg {self.egg_id} has been successfully hatched.")
The example defines the DinosaurEgg class with one method named hatch. The hatch method…