How to hide python module entities? with example wpaccuracy

please click here for more wordpress cource

In Python, you can hide module entities (e.g. functions, classes, variables) using the underscore _ symbol as a prefix to their names. This is known as “private” or “protected” access.

Here’s an example:


def public_function():
    print("This function is public.")

def _private_function():
    print("This function is private.")

class PublicClass:
    def __init__(self):
        print("This is a public class.")

class _PrivateClass:
    def __init__(self):
        print("This is a private class.")

In the example above, public_function and PublicClass are considered public entities that can be accessed from other modules, while _private_function and _PrivateClass are considered private entities that are not intended to be accessed from outside the module.

To use this module in another file, you can import it like this:


from my_module import public_function, PublicClass

public_function()    # This function is public.
obj = PublicClass()   # This is a public class.

# The following lines will result in an AttributeError because they attempt to access private entities.
# _private_function()
# obj2 = _PrivateClass()

Note that while private entities can still be accessed from outside the module, it is generally considered bad practice to do so, as it can lead to unexpected behavior and make the code harder to maintain.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *