call a public method on an instance of a class in python

To call a public method on an instance of a class in Python, you first need to create an instance of the class. This can be done by calling the class constructor. Once you have an instance of the class, you can call its public methods using the dot notation.

Here's an example code block to illustrate this:

main.py
class MyClass:
    def __init__(self):
        self.my_var = "hello"

    def public_method(self):
        print(self.my_var)

# create an instance of MyClass
my_instance = MyClass()

# call the public_method on my_instance
my_instance.public_method()
252 chars
13 lines

In the above code block, we define a class MyClass with an instance variable my_var and a public method public_method. We create an instance of this class with my_instance = MyClass(). Finally, we call the public method of my_instance using my_instance.public_method(). This will print "hello" to the console as defined in the public_method.

gistlibby LogSnag