Python Classes and Objects

Python is an interpreted high-level, structural, and object-oriented programming language. Since it is object-oriented, the concept of classes and objects is well-discussed and implemented. A class is the basis of object-oriented programming in Python. In this tutorial, we will learn about Classes and Objects in Python. A class is a template for an object, whereas an object is an instance of a class.

What is a class in Python

As discussed above, a class is a blueprint for objects in Python. We can easily create a class like this:

class name_of_class:
# Statement1
# Statement2
# Statement3
.
.
.
StatementN

Example 1 – Create a Class in Python

The class keyword is used to create a class in Python. The class is a reserved word in Python.

In the example below, we will see how to create a class in Python:

Demo85.py

# creating a class with a property val
# the class keyword is used to create a class
class Studyopedia:
  val = 100

print(Studyopedia)

Output

<class '__main__.Studyopedia'>

What is an object in Python?

An object is an instance of a class, i.e. object is created from a class. An object represents real-life entities, for example, a Bike is an object. The object has State, Behavior, and Identity:

  • Identity: Name of Bike
  • State (Attributes): The data of the object Bike i.e. Color, Model, Weight, etc.
  • Behavior (Methods): Behavior of object Bike like to Drive, Brake

Let us now see the representation, with Bike as an object:

Python Objects

Example 2 – How to Create a Class and an Object in Python

Considering the above example of classes in Python, we can easily create an object.

Demo86.py

# creating a class with a property val
# the class keyword is used to create a class
class Studyopedia:
  val = 100

print(Studyopedia)

# object ob
ob = Studyopedia()

# displaying the value using the object ob
print("Value = ",ob.val)

Output

<class '__main__.Studyopedia'>
Value =  100

Now, we can easily create a sample Python program on Classes and Objects. Let’s see.

Example 3 – Python Classes and Objects

Let us see an example to implement classes and objects in Python. In the class, we have used a function parameter self.

In Python, self is a special convention used inside class methods to refer to the current instance of the class.

Demo87.py

# class
class Bike:
     
    # attributes of Bike
    name = "Hayabusa"
    body = "GEN III"
    engine = 1340
 
    # Custom Python function
    def demoFunc(self):
        print("\nBike = ", self.name)
        print("Body = ", self.body)
        print("Engine (cc) = ", self.engine)
 
# Objects
b1 = Bike()
b2 = Bike()
 
# Accessing using the 1st object
print("Bike name = ",b1.name)
print("Bike Engine = ",b1.engine)

# calling using the 2nd object
b2.demoFunc()

Output

Bike name =  Hayabusa
Bike Engine =  1340

Bike =  Hayabusa
Body =  GEN III
Engine (cc) =  1340

Example 4 – Python Classes and Objects

# Classes and Objects in Python
# Example 3

class Car:
      # attributes of Car
      # class variables
      brand = "Tesla"
      model = "S"
      engine = 1020

      def show(self):
          print("Car Brand = ",self.brand)
          print("Model =",self.model)
          print("Engine =",self.engine)

# Class objects
c1 = Car()
c2 = Car()

# Access using the 1st object
print(c1.brand)
print(c1.model)

# call using the 2nd object
c2.show() # self refers to c2 because we are calling show() using c2

c1.brand = "Kia"
c1.model = "Sonet"
c1.engine = 1100
print(c1.brand)
print(c1.model)
print(c1.engine)

c2.brand = "Hyundai"
c2.model = "i20"
c2.engine = 1000
print(c1.brand)
print(c1.model)
print(c1.engine)

Output

Tesla
S
Car Brand =  Tesla
Model = S
Engine = 1020
Kia
Sonet
1100
Kia
Sonet
1100

What self Does

  • It represents the object that is calling the method.
  • It allows you to access attributes and methods of that particular object.
  • Without self, methods wouldn’t know which object’s data they should work with.

Key Points

  • self must be the first parameter in instance methods.
  • You can technically name it anything (like this or obj), but by convention, Python developers always use self.
  • When you call a method on an object, Python automatically passes the object itself as the first argument to the method.

Python _init_() Function

The classes in Python have __init__() function. Like constructors in Java, the __init__() function executes when the object gets created.

Why do we need __init__?

Using this method, easily assign values to object properties.

It’s a special method, often called a constructor, that gets executed automatically when you create an object from a class. Its purpose is to initialize the object’s attributes with default or user-provided values. The __init()__ is needed if you want to set up initial values for attributes when an object is created.

Use __init__() if you want to set up initial values for attributes when an object is created. The purpose of __init__() is to initialize the object’s attribute with default or user-provided values.

What if __init__ is not defined?

  • Python will still create the object even if you don’t define __init__().
  • If you don’t provide one, Python uses a default constructor that does nothing special.

So, __init__() is optional, but it’s extremely useful for making your classes flexible and meaningful.

Let us understand with an example, wherein we will create a class Students and values will be assigned using the __init__(). We have also created object functions.

Also, we created the objects explicitly in this example:

  • st1, st2, and st3 are variables that hold references to three different Students objects.
  • Each time we call Students(...), Python runs the __init__ method and assigns values to the object’s attributes.

Demo88.py

# Python __init__() Function
# init is short for initialization

class Students:
    # Use __init__(), if you want to setup initial values for attributes when an object is created.
    # the purpose of __init__ is to initialize the object's attribute with default or user-provided values.
    def __init__(self,sname, ssub, sgrade):
        self.sname = sname
        self.ssub = ssub
        self.sgrade = sgrade

    # custom function
    def demofunc(self):
        print("I am "+self.sname)
        print("I am interested in the Subject = "+self.ssub)

# creating 3 objects
st1 = Students("Amit", "Programming", "A")
st2 = Students("Rohit", "Science", "A+")
st3 = Students("Sam", "Maths", "B")

st1.demofunc()
st2.demofunc()
st3.demofunc()

Output

I am Amit
I am interested in the Subject = Programming
I am Rohit
I am interested in the Subject = Science
I am Sam
I am interested in the Subject = Maths

Above, we have also used the self parameter. The class methods in Python have the first parameter as self to access the class variable. A method with no argument should also have an argument self. However, we can give it any name. It is not mandatory to use the word self.

Python Tutorial (English)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More

Python - Get User Input
Python Sets With Examples
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment