To add a private property to a class in Python, we can use a naming convention that involves adding two leading underscores to the property name. This naming convention provides a form of name mangling that effectively makes the property private and prevents it from being accessed or modified outside the class.
Here's an example:
main.py267 chars11 lines
In the example above, we define a class MyClass
with two properties: public_prop
(which is a regular public property), and __private_prop
(which is a private property).
To access the private property from outside the class, we need to define a getter and/or a setter method. In this case, we define get_private_prop
and set_private_prop
methods that allow us to get and set the value of the private property.
Here's an example of how to use the class:
main.py393 chars11 lines
gistlibby LogSnag