المقال الثالث: البرمجة الكائنية التوجه (OOP) في Python. سنتعلم الفئات والكائنات والوراثة.
الفئات (Classes)
dog.py
class Dog:
# Class attribute
species = “Canis familiaris”
# 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 __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 تعليق