Methods in Python

Introduction

Object Oriented Programming (OOP) में methods बहुत महत्वपूर्ण भूमिका निभाते हैं।
Methods class के अंदर define किए गए functions होते हैं, जो object के behavior को represent करते हैं।

सरल शब्दों में, methods यह बताते हैं कि object क्या काम कर सकता है।

Method क्या होता है

Method एक function होता है, जो class के अंदर define किया जाता है और object के द्वारा call किया जाता है।

Basic Syntax

class ClassName:
def method_name(self):
statement

Example (Basic Method)

class Student:
def greet(self):
print("Hello Student")
s1 = Student()
s1.greet()

Output

Hello Student

Method कैसे काम करता है

  • Method class के अंदर define होता है
  • Object के द्वारा call किया जाता है
  • self object को represent करता है

self keyword का role

  • self current object को refer करता है
  • इसकी मदद से हम object के data (attributes) access करते हैं

Example (Method + self)

class Student:
def __init__(self, name):
self.name = name
def show(self):
print("Name:", self.name)
s1 = Student("Rahul")
s1.show()

Method के प्रकार (Types of Methods)

Python में methods मुख्य रूप से 3 प्रकार के होते हैं:

  1. Instance Method
  2. Class Method
  3. Static Method

1. Instance Method

यह सबसे common method होता है।
यह object के data (instance variables) को access करता है।

class Student:
def show(self):
print("This is instance method")
s1 = Student()
s1.show()

2. Class Method

यह class level पर काम करता है और class variables को access करता है।

class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
Student.show_school()

3. Static Method

यह method class या object से directly जुड़ा नहीं होता।

class Student:
@staticmethod
def greet():
print("Hello")
Student.greet()

Method with Arguments

class Student:
def greet(self, name):
print("Hello", name)
s1 = Student()
s1.greet("Amit")

Method with Return Value

class Calculator:
def add(self, a, b):
return a + b
c1 = Calculator()
print(c1.add(5, 3))

Real-life Example: Bank system

class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print("Balance:", self.balance)
acc = Account(1000)
acc.deposit(500)

Real-life Example: Car

class Car:
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
c1 = Car()
c1.start()
c1.stop()

Important Points

  • Method class के अंदर define होता है
  • Object के द्वारा call किया जाता है
  • self जरूरी होता है (instance method में)
  • Different types के methods होते हैं

Common mistakes

  1. self parameter भूल जाना
  2. method को call न करना
  3. class method और static method में confusion

Mini Program

class Person:
def greet(self):
print("Hello")
p1 = Person()
p1.greet()

Summary

Methods object के behavior को define करते हैं।
इनकी मदद से हम program को dynamic और functional बना सकते हैं।

Leave a Comment

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

Scroll to Top