How to create a class and object in python / Concept of class and object in python

What is a class
Concept of class can be better explained and understood by an example. Suppose an apartment of hundreds of flats need to be made. All the flats will be based on a design which is created by an architect. Now in future if more such flats need to constructed, then it can be easily done with the help of this design. This design can also be termed as a template or skeleton. Similar is the concept of a class.
A class in an Object Oriented Programming language is a template, skeleton, blue print or design based on which objects are created. A class contains variables(or fields) and methods. Once a class is created, any number of objects of that class can be created.

What is an object
Relating to the above example, a flat constructed from the design will be an object. As multiple flats can be created from the same design, multiple objects can be created from the same class.
An object can have a state and behavior as each flat can have its own color and interior design.
In technical terms, a class is a template with variables and method but each object will have different values of those variables. Also, each object will have different copies of variables and methods of its class. Below illustration will make it more clear.
Class and objectsAs evident from the above image, a class behaves as a blue print for its objects. Each object has a copy of the fields and methods of its class and each object can have different values of fields. Fields define the state and methods define the behavior of an object.

Field is also called class variable or instance variable

Syntax
Concept of class and object outlined till now is a generalized explanation of these two and is applicable to all Object Oriented Programming languages. But the syntax of creating classes and objects is different for every programming language.


For python the syntax of creating a class is as below

class <class name>:
# class variables
# constructor
# methods

A class is created using keyword class followed by a user defined class name and a colon(:) and then its variables, constructor and methods. Constructor and methods are optional, they are added as per the requirement. Everything that a class contains is called the body of the class. Remember that the body of class should be indented relative to class keyword. A sample class is shown below.

class Vehicle:
   # class variable
   color = "red"
 
   # class method
   def printMessage(self):
       print("This is a vehicle")
A class can be empty, that is it does not contain any methods or fields. An empty class is created using pass keyword using below syntax.
class Empty_class: pass

Constructor
A constructor is a special method which is primarily used to create class variables and define the method of creating objects. A constructor can accept arguments and if it does, then every object should be supply the values of those arguments for its creation. Sounds confusing but it will be clear after a few examples.
In many programming languages, a constructor of a class should be of same name as the class but in python, a constructor has a fixed name. It is created by the name init prefixed and suffixed by two underscores(__) followed by optional arguments. Example,

class Sample:
 
   # constructor without any arguments
   def __init__(self)
      print("This is a constructor")
 
   # method
   def sample_method():
      print("This is a method")

Following points must be remembered regarding constructors:
1. A constructor is optional and is primarily required when you want to declare class variables or perform some action while creating objects.
2. A constructor will always be called when an object of the class is created.
3. A constructor will always accept self as the first argument which represents the current object being created.
4. If a constructor accepts any arguments, then they should be placed after self.
5. Constructor in above example does not accepts any arguments.
6. If a constructor accepts any arguments, then equal number of values should also be given when objects are created.

Creating Object
An object in python is created using its class name followed by parenthesis. Parenthesis can be empty or contain arguments depending upon how the constructor is defined. Number of arguments should be same as given in the constructor. If no constructor is defined then the parenthesis will be empty.
An object is assigned to a user defined variable. This variable is later used as a handle to the object and can be used to call methods of a class or access its fields(class variables). It is called as the reference variable. Example,

# class begins
class Student:
 
   # define a class variable
   grade = "beginner"
 
   # constructor without any arguments
   def __init__(self):
      print("Constructor called")
 
   # method of class
   def printHello(self):
      print("Hello! I am a student of python")
# class ends
 
# create an object of class
st = Student()
# access class variables
print("Grade is "+st.grade)
# call its method
st.printHello()

Above code defines a class Student containing a class variable, constructor and a method. An object of this class is created and assigned to a variable st. This is a reference variable which is later used for accessing class variables and calling methods. Note that all methods of the class should have self as an argument. It refers to the current object.

Output of above code will be

Constructor called
Grade is beginner
Hello! I am a student of python

Note that when an object is created, constructor is automatically called and prints a message.

Now let’s look at using constructor with arguments. Below code declares a constructor that accepts one argument. Inside the constructor a class variable is created and initialized with the argument supplied to the constructor. Class variables(or instance variables) are created by prefixing them with self. where self references the current object for which the constructor is called. Also, self can be accessed anywhere inside the class.

# class begins
class Student:
 
   # define a class variable
   grade = "beginner"
 
   # constructor without any arguments
   def __init__(self, name):
      # create and initialize another class variable
      self.studentName = name
      print("Constructor called")
 
   # method of class
   def printName(self):
      # access class variable
      print("Hello! My name is "+self.studentName)
# class ends
 
# create an object of class, assign it to reference variable
st = Student("codippa")
# call its method
st.printName()
# access class variables
print("Grade is "+st.grade)
print("Class variable is "+st.studentName)

Class also declares a method printName which prints the value of class variable. Now an object of this class is created and it is used to call method printName and to print the value of class(or instance) variable. Notice that while creating the object, an argument is supplied within the parenthesis since constructor also takes 1 argument. Also, the object is used to access the class variable grade. Output is

Constructor called
Hello! My name is codippa
Grade is beginner
Class variable is codippa

If the number of arguments expected by the constructor and those supplied while creating object are not equal, then an error will be raised. Suppose in above example, if the object is created as st = Student(), then you will get TypeError: __init__() missing 1 required positional argument: ‘name’

It is not necessary for the first argument to be named as self. It can be any name but whatever it is, the first argument will refer to the current object. Example,

class Student:
   def __init__(mystudent, n):
      # create class variable
      mystudent.name = n

Creating multiple Objects
As stated earlier, once a class is defined, any number of objects can be created. Object creation follows the same syntax as explained above. Each new object should be assigned to a different reference variable. Below code creates 4 objects of Student class defined above.

st1 = Student("John")
st2 = Student("Peter")
st3 = Student("George")
st4 = Student("Michael")

Each object will have its own copy of class variables and methods. If one object modifies its variables, it will have no effect on variables of other objects.
If two objects are assigned to the same reference variable, then later reference will point to the second object while the first object will have no reference and it will not be possible to access it.

Deleting Object variables
As explained above, each object has its own set of variables(also called instance variables or object properties). It is possible to create object variables dynamically using self(or whatever the first constructor argument is named). Once object properties are created, it is also possible to remove them. An object variable or property is removed by using del keyword. Example, (class template is not shown, refer examples above)

# create an object of class
st = Student("codippa")
# call its method
st.printName()
# access class variable
print("Class variable is "+st.studentName)
# delete object variable
del st.studentName

It is not possible to access object properties after they are deleted. Trying to access a deleted property will raise an error. Thus, if the following statement is written after the above piece of code, then it will raise an error

print(st.studentName)

AttributeError: ‘Student’ object has no attribute ‘studentName’

Deleting Object
Just as it is possible to delete object variables, it is also possible to delete the entire object. This is also done using del keyword as shown below.

# create an object of class
st = Student("codippa")
# call its method
st.printName()
# delete object
del st

Once deleted, the object can not be accessed. If it is accessed, an error will be raised. Thus, if the following statement is written after the above piece of code, then it will raise an error

print(st.studentName)

NameError: name ‘st’ is not defined
For any sort of queries/clarifications, comment in the space below.

Mark Your Impression

Close Menu