دروس تعليمية متوسط

تعلم Python للمبتدئين — الجزء 3

1 دقيقة قراءة
Python, OOP
01 المقدمة
02 المتطلبات
03 التثبيت
04 الإعداد
05 التطبيق
06 النتيجة
07 الخطوة 7
08 الخطوة 8

المقال الثالث: البرمجة الكائنية التوجه (OOP) في Python. سنتعلم الفئات والكائنات والوراثة.

الفئات (Classes)

dog.py

class Dog:
  # Class attribute
  species = “Canis familiaris”

  # Initializer
  def __init__(self, name, age):
    self.name = name
    self.age = age

  # Instance method
  def bark(self):
    return f“{self.name} ينبح!”

  # String representation
  def __str__(self):
    return f“{self.name} ({self.age} سنة)”

# Create instances
dog1 = Dog(“رفيق”, 3)
dog2 = Dog(“صديقي”, 5)

print(dog1.bark()) # رفيق ينبح!
print(dog2) # صديقي (5 سنة)

الوراثة (Inheritance)

animals.py

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

  def speak(self):
    raise NotImplementedError

class Cat(Animal):
  def speak(self):
    return f“{self.name} يقول: мяу!”

class Dog(Animal):
  def speak(self):
    return f“{self.name} يقول: هاو!”

0 تعليق

أضف تعليقاً