Classes And Objects In Python

CLASSES AND OBJECTS IN PYTHON

Usually, the terminology in which people gets confused is as follows:

Classes, Objects and in Python keywords like _init_  , _name_, etc., or is self a keyword? So, in this article, we will clear our concepts of classes and objects, will know the difference and relationship between the two, and how the implementation is done in OOPs concept (Refer to my previous article).

What is an Object?

  • Every real-world entity is an object, so basically everything surrounding you is an object like tree, pencil, pen, laptop, etc.
  • For everything you need objects, so to solve real-world issues/problems, we need objects.
  • For example-To write this article, I need my laptop. So, laptop is an object here.
  • Objects have 2 characteristics:
    • Behaviour
    • Attributes/Properties

Let us understand this with the help of an example.

I am Aashina. I write articles then sleep for sometime and then eat snacks and drink coffee. Here;

  • Object is Aashina
  • Attributes are my name, my age, my height
  • Behaviour is writing, sleeping, drinking, and eating.

**NOTE: Everything is an Object in Python

What is a Class?

Classes and objects are interrelated. Now you must be wondering how?

  • In class, we write design of a particular object.
  • Class- Design/Blueprint
  • Object- Instance/Real-World Entity
  • For example- Before building a tower, an architect creates a blueprint.

Above is a blueprint so you can consider it as a class louvre.

Above is the final product, so louvre here is real-world entity i.e. an object.

So basically, before creating an object, you need to create a class. Logically, unless you don’t have a design or a structure, you cannot produce or create an object.

SYNTAX OF CLASS

class class_name:
#body of class

Body of a class consists of:

  • Attributes- Variables (These are used to save data)
  • Behaviours- Methods (These are used to perform specific operations)

Structure of a class

class MyClass:  #creating a class

  def method_example(self):    #method/function definition
      print("This is my Method")  #method body

object_example = MyClass()  #Object with constructor
print(object_example)
print(type(object_example))
MyClass.method_example(object_example)  #method calling
object_example.method_example()  #another way of method calling

Output

In case you want the class to remain empty and not throw any error, then use:

class MyClass:
  pass

Understanding __init__

  • __init__ is a special method in Python OOPS which is used to initialize a variable.
  • For every object __init__ is called once.

For example,

class MyClass:

  def __init__(self):
    print("Inside init")

obj1= MyClass()
obj2= MyClass()

Output

As you can see in the above example, both the objects will print the same value this is because init have only one argument i.e. ‘self ‘ and only one print statement ‘Inside Init ‘ and a we know that for every object ‘ init ‘ is called once.

Question: How can you assign a different value to a different object?

class MyClass:

  def __init__(self,arg1,arg2):
    self.arg1=arg1
    self.arg2=arg2

  def myMethod(self):
    print("myMethod is:", self.arg1,self.arg2)

obj1= MyClass('a','b')
obj2= MyClass('c','d')
obj1.myMethod()
obj2.myMethod()

Output

Now you must be wondering that in above example __init__ has 3 arguments but when object creation is done, obj1=MyClass(‘a’,’b’) – this statement have only 2 arguments. Why?

This is because, in the backend MyClass(‘a’,’b’,’obj1’) has 3 arguments, third one is obj1.

Understanding Constructor

After looking at all the above examples, you must be wondering that who allocates size to an object! – Yes! It’s a Constructor.

  • Constructors are used to initialize or assign the values. In python, __init__ is the constructor and as discussed before also, it is called when object is created.
  • Constructor calls __init__ method automatically and internally.

Question: How and where objects are saved?

Answer: There is a concept named- Heap Memory

In this memory, all the objects are saved in one place. It is a storage location where every object is assigned an address. So, every time you create an object it is allocated to a new space.

For Example,

class MyClass:

  def __init__(self):
    pass

obj1= MyClass()
obj2= MyClass()
print(id(obj1))
print(id(obj2))

Output

The method id() gives you the address location of the particular object. So, according to the above example, we created 2 objects and both objects have different memory location in the Heap Memory as you can see in the output.

Question: What is the size of an object?

Answer: It depends on the number of variables and size of each variable

Question: How you can change values of the object, if it is pre-defined?

class MyClass:

  def __init__(self):
    self.first_name='Aashina'
    self.last_name='Arora'

obj1= MyClass()
obj2= MyClass()
obj1.first_name='Sneha'
print(obj1.first_name, obj1.last_name)
print(obj2.first_name, obj2.last_name)

Output

Understanding 'self'

Most common question and doubt are that; Is “Self” a keyword? What is “self” used for?

Let’s clear these questions.

‘self’ is used to refer to an object so it refers to the current instance/object.

For example,

class MyClass:

  def __init__(self):
    self.first_name='Aashina'
    self.last_name='Arora'

  def compare_text(self,other):
    if self.last_name==other.last_name:
      return True
    else:
      return False

obj1= MyClass()
obj1.last_name='arora'
obj2= MyClass()

if obj1.compare_text(obj2):
  print('Same!!')
else:
  print('Different!!')

Output

The output is different because last_name was case sensitive.

**Note- ‘self’ is not a keyword.

Your program will work if you replace ‘self’ with any other word or variable but it will not work if it is not at all present. Meaning:

class MyClass:

  def __init__(notSelf):
    print("Inside init")

obj1= MyClass()
obj2= MyClass()

Output

This program will work, we have replaced ‘self’ with another word i.e. ‘notSelf’

But it will not work or run, if we remove it. This is because, it is representing instance of the class and will help you to access the attributes and methods of the class. Meaning:

class MyClass:

def __init__():
print("Inside init")

obj1= MyClass()
obj2= MyClass()

Output

Summary

In this article, we learned about classes and objects in Python. We cleared our concepts of what are classes, objects and how they are inter-related. I hope now you are confident with topics like constructor, __init__ and “self”.

This was first part of classes and objects and there’s more! So, in my next article, i.e. Variables, Methods and Inner Class In Python , we will learn more concepts like types of variables, methods and Inner class, etc.

Thanks for reading!!