How to Check the Return Type of a Python Class with Type Hinting?

Estimated read time 2 min read

To check the return type of a Python class using type hinting, you can make use of the typing module. By annotating the return type of a class method using type hints, you can provide information about the expected return type. Here’s an example:

from typing import Type

class MyClass:
    def __init__(self, value: int):
        self.value = value
    def get_value(self) -> int:
        return self.value

# Create an instance of MyClass
obj = MyClass(10)

# Check the return type of the method
return_type = Type[obj.get_value]

# Print the return type

In the code above, we define a class called MyClass with an __init__ method and a get_value method. The get_value method is annotated with -> int to indicate that it returns an integer.

To check the return type, we create an instance of MyClass and assign it to the variable obj. Then, we use Type[obj.get_value] to retrieve the return type of the get_value method and assign it to return_type. Finally, we print the return type using the print() function.

The output will be <class 'int'>, indicating that the return type of the get_value method is an integer.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply