To add a private method to a class in Python, you can use a prefix underscore (_) to indicate that the method is intended to be used only within the class and should not be accessed outside of it. Here's an example:
main.py336 chars12 lines
In the example above, we have defined two methods, public_method
and _private_method
. The public_method
is a regular method that can be accessed from outside of the class, but it calls the _private_method
, which is marked as private using a single underscore prefix. This means that _private_method
should not be called outside of the class.
To create an instance of MyClass
, you can do the following:
main.py22 chars2 lines
And then you can call the public method, which will in turn call the private method:
main.py89 chars5 lines
Note that the use of the single underscore by convention indicates that the method should not be accessed outside of the class, but it doesn't enforce it. You can still access the method from outside of the class if you really want to, although it's not recommended.
gistlibby LogSnag