🐍 کتابخانه مرجع پایتون

🏛️ کلاس‌ها و برنامه‌نویسی شیءگرا (OOP)

برنامه‌نویسی شیءگرا (Object-Oriented Programming) یک پارادایم است که داده‌ها و توابع را در قالب کلاس‌ها و اشیاء سازمان‌دهی می‌کند. در این روش، کدها به صورت ماژولار، قابل استفاده مجدد و قابل فهم‌تر نوشته می‌شوند.

🔹 تعریف کلاس و ایجاد شیء

# تعریف یک کلاس ساده
class Car:
    # متد سازنده (__init__)
    def __init__(self, brand, model):
        self.brand = brand  # ویژگی (attribute)
        self.model = model

    # متد (method)
    def start(self):
        print(f"{self.brand} {self.model} is starting...")

# ایجاد شیء (object)
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")

# دسترسی به ویژگی‌ها و متدها
print(car1.brand)  # Toyota
car2.start()       # Honda Civic is starting...
⏳ برای اجرا دکمه را بزنید...

🔹 متد __init__ (سازنده)

متد __init__ زمانی فراخوانی می‌شود که یک شیء جدید از کلاس ساخته می‌شود.

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade
        print(f"Student {name} created!")

# ایجاد اشیاء
student1 = Student("Saba", 22, 18)
student2 = Student("Ali", 24, 15)
⏳ برای اجرا دکمه را بزنید...

🔹 متدها (Methods)

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

    def info(self):
        print(f"Rectangle: {self.width}x{self.height}")
        print(f"Area: {self.area()}")
        print(f"Perimeter: {self.perimeter()}")

# استفاده
rect = Rectangle(5, 3)
rect.info()
⏳ برای اجرا دکمه را بزنید...

🔹 ویژگی‌های کلاس در مقابل شیء

class Dog:
    # ویژگی کلاس (مشترک بین همه اشیاء)
    species = "Canis familiaris"

    def __init__(self, name, age):
        # ویژگی شیء (مخصوص هر شیء)
        self.name = name
        self.age = age

dog1 = Dog("Rex", 3)
dog2 = Dog("Bella", 5)

print(dog1.species)  # Canis familiaris
print(dog2.species)  # Canis familiaris

# تغییر ویژگی کلاس
Dog.species = "Canis lupus familiaris"
print(dog1.species)  # Canis lupus familiaris
⏳ برای اجرا دکمه را بزنید...

🔹 ارث‌بری (Inheritance)

کلاس‌ها می‌توانند از کلاس‌های دیگر ارث‌بری کنند و ویژگی‌ها و متدهای آن‌ها را بگیرند.

# کلاس والد (Parent)
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

# کلاس فرزند (Child)
class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

# استفاده
cat = Cat("Kitty")
dog = Dog("Rex")

print(cat.speak())  # Kitty says Meow!
print(dog.speak())  # Rex says Woof!
⏳ برای اجرا دکمه را بزنید...

🔹 متد super()

با super() می‌توان به متدهای کلاس والد دسترسی داشت.

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

class Bird(Animal):
    def __init__(self, name, species, wingspan):
        super().__init__(name, species)  # فراخوانی سازنده والد
        self.wingspan = wingspan

    def info(self):
        return f"{self.name} is a {self.species} with {self.wingspan} cm wingspan."

# استفاده
sparrow = Bird("Sparrow", "Passer domesticus", 20)
print(sparrow.info())
⏳ برای اجرا دکمه را بزنید...

🔹 ارث‌بری چندگانه

پایتون از ارث‌بری از چند کلاس والد پشتیبانی می‌کند.

class Flyable:
    def fly(self):
        return "Flying..."

class Swimmable:
    def swim(self):
        return "Swimming..."

class Duck(Flyable, Swimmable):
    def __init__(self, name):
        self.name = name

    def info(self):
        return f"{self.name} can {self.fly()} and {self.swim()}"

# استفاده
duck = Duck("Donald")
print(duck.info())
⏳ برای اجرا دکمه را بزنید...

🔹 متدهای ویژه (Magic Methods)

متدهای ویژه با دو زیرخط شروع و پایان می‌یابند و رفتار خاصی را تعریف می‌کنند.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # __str__: نمایش قابل فهم برای کاربر
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    # __repr__: نمایش برای توسعه‌دهندگان
    def __repr__(self):
        return f"Vector(x={self.x}, y={self.y})"

    # __add__: عملگر +
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    # __eq__: عملگر ==
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

# استفاده
v1 = Vector(2, 3)
v2 = Vector(1, 4)

print(v1)                    # Vector(2, 3)
print(v1 + v2)               # Vector(3, 7)
print(v1 == Vector(2, 3))    # True
⏳ برای اجرا دکمه را بزنید...

🔹 خصوصی‌سازی (Encapsulation)

با استفاده از _ (protected) و __ (private) می‌توان دسترسی را محدود کرد.

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner          # عمومی (public)
        self._type = "savings"      # محافظت‌شده (protected)
        self.__balance = balance    # خصوصی (private) - با name mangling

    def get_balance(self):
        """دسترسی به مقدار خصوصی از طریق متد"""
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return True
        return False

# استفاده
account = BankAccount("Saba", 1000)

print(account.owner)          # Saba
print(account._type)          # savings (با وجود protected، قابل دسترس است)
print(account.get_balance())  # 1000

# دسترسی مستقیم به private ممکن نیست (خطا می‌دهد)
# print(account.__balance)
⏳ برای اجرا دکمه را بزنید...

🔹 @property و @setter

با @property می‌توان متدها را به صورت ویژگی استفاده کرد.

class Person:
    def __init__(self, first_name, last_name):
        self._first_name = first_name
        self._last_name = last_name

    @property
    def full_name(self):
        return f"{self._first_name} {self._last_name}"

    @full_name.setter
    def full_name(self, name):
        parts = name.split()
        if len(parts) == 2:
            self._first_name, self._last_name = parts
        else:
            print("Please provide first and last name.")

# استفاده
person = Person("Saba", "Ahmadi")
print(person.full_name)    # Saba Ahmadi

person.full_name = "Ali Rezaei"
print(person.full_name)    # Ali Rezaei
⏳ برای اجرا دکمه را بزنید...

🔹 مثال جامع: سیستم مدیریت کتابخانه

class Book:
    def __init__(self, title, author, isbn):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.is_borrowed = False

    def __str__(self):
        status = "Available" if not self.is_borrowed else "Borrowed"
        return f"'{self.title}' by {self.author} (ISBN: {self.isbn}) - {status}"

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []

    def add_book(self, book):
        self.books.append(book)
        print(f"Book '{book.title}' added to library.")

    def find_book(self, title):
        for book in self.books:
            if book.title.lower() == title.lower():
                return book
        return None

    def borrow_book(self, title):
        book = self.find_book(title)
        if book and not book.is_borrowed:
            book.is_borrowed = True
            print(f"You borrowed '{book.title}'")
            return True
        elif book and book.is_borrowed:
            print(f"'{book.title}' is already borrowed.")
        else:
            print(f"Book '{title}' not found.")
        return False

    def return_book(self, title):
        book = self.find_book(title)
        if book and book.is_borrowed:
            book.is_borrowed = False
            print(f"Thank you for returning '{book.title}'")
            return True
        elif book and not book.is_borrowed:
            print(f"'{book.title}' is not borrowed.")
        else:
            print(f"Book '{title}' not found.")
        return False

    def show_books(self):
        print(f"\n--- {self.name} Library ---")
        if not self.books:
            print("No books in library.")
            return
        for book in self.books:
            print(book)
        print("---\n")

# استفاده
library = Library("City Library")

# اضافه کردن کتاب‌ها
library.add_book(Book("Python Programming", "John Doe", "123-456"))
library.add_book(Book("Data Science 101", "Jane Smith", "789-012"))
library.add_book(Book("AI Basics", "Alan Turing", "345-678"))

# نمایش کتاب‌ها
library.show_books()

# قرض گرفتن و برگرداندن
library.borrow_book("Python Programming")
library.borrow_book("Python Programming")  # قبلاً قرض گرفته شده

library.show_books()

library.return_book("Python Programming")
library.show_books()
⏳ برای اجرا دکمه را بزنید...

📌 نکات کلیدی

← قبلی: ماژول‌ها → بعدی: کامپرهنشن‌ها ↑ بازگشت به فهرست مقدماتی