Understanding the Class and Object in Python

In this Python article, we will discuss every detail of the classes in python and how can we use classes in python. Also the different class methods like self, and different types of objects with lots of examples.

1. What is a class in Python and how to use them?

As we discussed in our OOP tutorial, class is a feature of OOP. In simple words, class is a blueprint of an object which contains the definition of various methods and variables.

Structure of Class

For creating a big structure or any machine, the blueprint is a crucial thing, in the same way, the class acts as the blueprint of its objects and defines data(variables) what an object will contain and what all behaviors(methods) it can have.

It can be understood with a small example, we all belong to one class of Human Being, yet we are all different objects. If we have to design a class for HumanBeing then it can have data like height, age, country, dob, and many more. Similarly, the behaviors (methods) will look something like eat, walk, sleep, laugh, run, love, etc.

A class has some data which describes the state of the objects and the functions perform different operations. These operations are mainly performed on the data of the object.

Let’s understand the above concept better. Suppose, we have a class named Machine, which requires some data such as power, manufacturedDate, outputRate, brand, speed, efficiency, cost, currentStatus, and purpose. It also contains certain functions like powerOn(), performWork(), workStatus(), fuelStatus(), maintenance(), and several others

Now we can initialize and create multiple objects of Machine, all of those data can contain its own data and we can use the functions to change or access the state of the object. For example, powerOn() function can change the currentStatus of the Machine and can also start calculating the power consumed or the output generated.

class ClassName:     
  <<class body>>

1.1. What is ‘self’ in Python class?

Classes in python have an additional parameter as the first parameter while defining the methods. It is compulsory to have the self keyword. Python by itself assigns value to this parameter after the method is called.

self keyword refers to the current object.

Minimum one argument( self ) has to be present in the method even if we do not have other arguments to pass in the method.

this pointer of C++ and this refernce in Java are alike to the self in python.

Suppose we have a class with the name ‘ SuperHuman ‘ and we have an object batman. We can now use batman to call the method inside the class superhuman as batman.anymethod(arg1, arg2) which gets converted into SuperHuman.anymethod(batman, arg1, arg2) – this is the effect of self.

class SuperHuman:

  # attribute init
  name = "Bruce Wayne"
  power = "super strong"

  def tagline(self):
    print(f"My name is: {self.name}",
          f"and my character is {self.power}")

# Driver code
# initalising object
bat = SuperHuman()
My name is: Bruce Wayne and my character is super strong

1.2. What is __init__ or Constructors in Python class?

We define the __init__ method as the constructor of the class.

A constructor is a method that is called whenever instantiation of an object.

Every class has one __init__() method which is always executed during the object creation. This function is called automatically and we do not need to explicitly call it.

The use of __init__() function is to assign values to attributes of an object, or other operations that are necessary to do when the object is being created.

class Employee:

  # init method/constructor
  def __init__(self, emp_name):
    print("__init__ => will do initializatioon tasks")
    self.name = emp_name

  def greet(self):
    print("Hello", self.name)

e1 = Employee('James')
init => will do initializatioon task
Hello James

2. What is an Object in Python?

We can define an object as an instance of a class. The class only describes the details of the object or the blueprint of the object.

An object needs to be initialized and it takes the memory in the system.

The creation of a new object or instance is called instantiation.

Different data types like integer, string, float, array, dictionaries, all are objects.

Some examples of an object are

  • A variable with the value 5 is an object
  • A string with ‘codingeek’ as a value is an object
  • A list containing different items is an object
  • A list can also hold different objects, and this list can go on and on.
object_name = classname(provided parameters)
# object_1 = machine(power, manufactured date, cost, brand)

2.1. Creating an Object In Python

To create an object we use the name of the class followed by parentheses(and arguments if required).

The procedure to create an object looks like a normal function call.

e1 = Employee('James')

This will create a new object instance named e1. We can access the attributes of objects using the object name prefix.

Attributes may be data or method. Methods of an object are corresponding functions of that class.

2.2. Python Instance Variables vs Class Variables

Instance variables are variables whose value is assigned inside a constructor or method with self. Instance variables values can be different for each object.

Class variables are variables whose value is assigned in the class. These variables have the same values for all the objects. They are not defined inside any methods of a class.

Both class and instance variables can be changed and by default, they are not constant.

Let’s implement an example for class variables and instance variables.

class Coding:

  # Class Variable
  platform = "codingeek.com"

  # The init method or constructor
  def __init__(self, leader, team):

    # Instance Variables
    self.leader = leader
    self.team = team

# Objects of Dog class
member1 = Coding("A good leader", "A good team")
member2 = Coding("A better leader", "A better team")

print('Member 1 detail:')

print('\nMember 2 detail:')
Member 1 detail:
A good leader
A good team

Member 2 detail:
A better leader
A better team
class Machine:
  # attribute inside the class
  motor = "DC"      

  def __init__(self, price, power, brand):
    # instance variables
    self.price = price
    self.power = power
    self.brand = brand

# Object instantiation
washing_machine = Machine(12000, "50 Watt", "Samsung")
air_conditioner = Machine(22000, "130 Watt", "Samsung")

# accessing each attribute of class
print("First machine: Price", washing_machine.price, "Power consumption",
      washing_machine.power, "Brand", washing_machine.brand)
print("Second machine: Price", air_conditioner.price, "Power consumption",
      air_conditioner.power, "Brand", air_conditioner.brand)
First machine: Price 12000 Power consumption 50 Watt Brand Samsung
Second machine: Price 22000 Power consumption 130 Watt Brand Samsung

Easily, we can modify variables, we can delete any variable, we can even modify the object’s value and we can delete the variable.

2.3. What is Method Object in Python?

A method is a function that “belongs to” an object. By definition, all attributes of a class that are function objects define corresponding methods of its instances. So in our example, x.greet is a valid method reference because MyClass.greet is a valid function.

If we call  x.greet then it will return hello world instantly but we can save the reference like xGreet = x.greet of the method as a method object and can invoke it multiple times like xGreet(). This will also make sure that it invokes the method on the correct object.

class MyCLass:

  def greet(self):
    return 'hello world'

x = MyCLass()
print(f"Direct functioon call - {x.greet()}")

# method object
xGreet = x.greet
print(f"Using method reference - {xGreet()}")
Direct functioon call - hello world
Using method reference - hello world

3. Conclusion

Finally, if we sum up, in this article we learned everything about class and object in OOP along with their implementation and examples.

  • What is a class and an object in Python?
  • What is the purpose of __init__ function and self variable in a class?
  • What are instance objects and method objects along with their uses?

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x