An instance is a case or occurrence of any object, existing usually during the runtime of a computer program
In a broader sense, for example, when an application is opened by an user, then the underlying program creates an instance of the application, which exists till the application is closed
When the user closes the application and reopens, then another instance of the application is created
Although the user might not be aware due to no visible difference while restarting a program, most programs work by creating instances
Such implementation helps in releasing resources like Ram etc when an application is closed, or during its runtime
In programming, an object is an instance of a class, and may be called as class object or class instance
A class
defines the structure and properties that any object created for that class can have
The process of creating an object from a class is called as instantiation
It can be as simple as calling the class name like a function
class Person:
name=""
person1 = Person()
person.name = "Mr X"
In above example, Person is a simple class and person1 is its object
In the line person1 = Person()
, the object person1
is instantiated from class Person
Instantiation is done through something called as constructor
which is a method or function of a class
Above program didn't declare a constructor, so Python creates a constructor for it when it is run and uses it to instantiate
Same program can be modified to declare a constructor, such as
class Person:
name=""
def __init__(self, name_argument):
self.name = name_argument
person1 = Person("Mr X")
Here, __init__(self, name_argument)
is the constructor which initialises (performs the initial steps of creating) the object
This allows the name
attribute of the class Person
, to be set when its object is created
Both the examples does the same thing of creating an object of class Person
with name Mr X
Not all classes can be instantiated - abstract classes cannot be instantiated