How to Return an Object in Python?

Estimated read time 1 min read

In Python, you can return an object from a function just like you would return any other value. An object can be an instance of a class, a data structure, or any other Python object. Here’s a simple example:

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

def create_object():
    obj = MyClass(10)
    return obj

result = create_object()
print(result.value)  # Output: 10

In the code above, the create_object() function creates an instance of the MyClass class and assigns it to the obj variable. The function then returns this object.

When the function is called, the returned object is stored in the result variable. You can access the attributes and methods of the object just like you would with any other object. In this example, result.value accesses the value attribute of the returned object and prints 10.

You can return any Python object, whether it’s a simple data type, a custom class instance, or a built-in object. The returned object can be used and manipulated in the calling code as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply