Python Objects – Step-by-Step Guide for Beginners

In Python, everything is an object – yes, even numbers, strings, and functions!

Let’s understand what objects are, how they work, and how you can create your own.


🔹 Step 1: What is an Object?

An object is a collection of data (variables) and behaviors (functions/methods). Think of an object as a real-world thing that has:

  • Properties (like name, color, age)
  • Actions (like speak, walk, drive)

📌 Example: A Car is an object. It has properties like brand, model, color and actions like start(), stop(), drive().


🔹 Step 2: Objects Are Created from Classes

A class is like a blueprint. You use it to create objects.

📦 Class = Design
🚗 Object = Real item built from that design


🔹 Step 3: Define a Class in Python

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def greet(self):
        print(f"Hi, I am {self.name} and I am {self.age} years old.")

 Explanation:

  • class Person: → defines a new class called Person
  • __init__() → a special method that runs when an object is created (like a constructor)
  • self → refers to the current object
  • greet() → a method (function inside the class)

 Step 4: Create Objects from the Class

p1 = Person("Asha", 25)
p2 = Person("Ravi", 30)
p1.greet()  # Output: Hi, I am Asha and I am 25 years old.
p2.greet()  # Output: Hi, I am Ravi and I am 30 years old.

Now, p1 and p2 are objects (also called instances) of the class Person.


🔹 Step 5: Add More Methods

You can add more functions (called methods) inside the class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hi, I am {self.name} and I am {self.age} years old.")
        
    def checkvote(self):
        if(self.age>=18):
            print("Eligible to Vote")
        else:
            print("Not Eligible to Vote")

a1=Person("Asha",10)
a1.greet()
a1.checkvote()


ConceptReal Life Example
ClassMobile phone design
ObjectReal phone in your hand
AttributeBrand, model, price
MethodCall, message, camera

Example :

class student:
    def __init__ (self,rollno,stname,m1,m2,m3,m4,m5):
        self.rollno=rollno
        self.stname=stname
        self.m1=m1
        self.m2=m2
        self.m3=m3
        self.m4=m4
        self.m5=m5

    def result(self):
        total=self.m1+self.m2+self.m3+self.m4+self.m5
        print("Total = ",total)

    def welcome(self):
        print("Welcome : ",self.stname)
        
s1=student(1001,'Raja',100,100,80,70,90)
s2=student(1002,'Kumar',100,100,80,100,90)
s1.welcome()
s1.result()
s2.welcome()
s2.result()

Output

Welcome : Raja
Total = 440
Welcome : Kumar
Total = 470

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *