add a protected method to a class in python

To add a protected method to a class in Python, you can prefix the method name with a single underscore. This indicates to other developers that the method is intended for internal use only, and should not be called from outside the class. Here is an example:

main.py
class MyClass:
    def __init__(self):
        self._my_protected_variable = "Hello, world!"
    
    def public_method(self):
        self._protected_method()
    
    def _protected_method(self):
        print(self._my_protected_variable)
241 chars
10 lines

In this example, MyClass has a public_method that can be called from outside the class, which in turn calls the _protected_method method. The underscore prefix indicates that _protected_method is intended for internal use only, and should not be called from outside the class. Note that this is just a convention, and it is still possible to call _protected_method from outside the class if you really want to.

gistlibby LogSnag