🔹 Classes and Objects in Python
Python is an object-oriented programming (OOP) language. This means it allows you to create and use classes and objects—which helps you organize and reuse code easily.
🔸 What is a Class?
A class is like a blueprint for creating objects. Think of a class as a design for a car. It defines what a car is (wheels, engine, doors), but it's not a real car yet.
Example:
class Car:
# attributes and methods go here
pass
🔸 What is an Object?
An object is a real-world instance of a class. If a class is the blueprint, then an object is the actual car built using that blueprint.
Example:
my_car = Car()
Now my_car
is an object of the Car
class.
🔸 Let’s Build a Real Example
Let’s create a class that represents a Person with a name and age, and a method to display their info.
✅ Example:
class Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age # attribute
def greet(self): # method
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating objects
person1 = Person("Surya", 25)
person2 = Person("Pawan", 30)
# Calling methods
person1.greet()
person2.greet()
💡 Output:
Hello, my name is Surya and I am 25 years old.
Hello, my name is Pawan
and I am 30 years old.
🔸 Breaking It Down
Part | Description |
---|---|
class Person: |
Defines a class called Person |
__init__ |
A special method called a constructor; runs when you create an object |
self |
Refers to the current object (must be the first parameter in methods) |
self.name = name |
Assigns the input to the object's attribute |
greet() |
A method that prints a message using the object’s data |
🔸 Another Example: A Simple Bank Account
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"{amount} deposited. New balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"{amount} withdrawn. New balance: {self.balance}")
else:
print("Insufficient balance!")
# Create an account
account = BankAccount("John", 1000)
# Use the methods
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)
💡 Output:
500 deposited. New balance: 1500
300 withdrawn. New balance: 1200
Insufficient balance!
🔚 Summary
-
A class defines the structure and behavior (attributes and methods).
-
An object is a real example of the class.
-
Use
__init__
to initialize object attributes. -
Use
self
to refer to the current object inside the class. -
Classes help keep your code organized, reusable, and clean.
No comments:
Post a Comment