As we have already discussed, a class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let's understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor, doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can be seen as a class, and we can create as many objects of this class.
On the other hand, the object is the instance of a class. The process of creating an object can be called as instantiation.
In this section of the tutorial, we will discuss creating classes and objects in python. We will also talk about how an attribute is accessed by using the class object.
In python, a class can be created by using the keyword class followed by the class name. The syntax to create a class is given below.
class ClassName: #statement_suite
In python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as Employee id, and name.
The class also contains a function display() which is used to display the information of the Employee.
class Employee: id = 10; name = "ayush" def display (self): print(self.id,self.name)
Here, the self is used as a reference variable which refers to the current class object. It is always the first argument in the function definition. However, using self is optional in the function call.
A class needs to be instantiated if we want to use the class attributes in another class or method. A class can be instantiated by calling the class using the class name.
The syntax to create the instance of the class is given below.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above example.
class Employee: id = 10; name = "John" def display (self): print("ID: %d \nName: %s"%(self.id,self.name)) emp = Employee() emp.display()