add a public method to a class in python

To add a public method to a class in Python, you can simply define a regular function inside the class definition. Here's an example:

main.py
class MyClass:
    def __init__(self, value):
        self.value = value

    def public_method(self):
        return self.value * 2
133 chars
7 lines

In this example, public_method is a regular function defined inside MyClass. It has access to the instance variables of MyClass, including self.value.

To call the public method from outside the class, you can create an instance of the class and call the method on it:

main.py
my_object = MyClass(10)
result = my_object.public_method()  # result is 20
75 chars
3 lines

By default, all methods in Python are public, as Python does not have a concept of private or protected methods like some other programming languages. However, it is still considered good programming practice to use encapsulation to protect the internal state of objects, and to only expose methods that are intended to be used by external code.

gistlibby LogSnag