Search code examples
pythonclassinstantiation

Instantiating a Python object in Visual Studio Code


I am new to Python and wonder if someone can help me with this simple query.

In Visual Studio Code I have created a class in a .py file. I have then run the file.

My question is how do I actually instantiate an object? I have tried unsuccessfully to do this in the Terminal window.

Thanks

Clos


Solution

  • Assume that you have created a script called test.py. And in this script you've created a class called Example like so:

    Class Example:
        def __init__(self):
            print("Example() instance is created!!")
    

    Now, you can instantiate this class using:

    x = Example()
    

    But if you want to use this class in the terminal, then you need first to import the class like so:

    $ python #to enable python shell in terminal
    >>> from test import Example
    >>> x = Example()
    Example() instance is created!!