مراجعة اليوم: self - “أنا وأنا وأنا!”
العربية
:
تخيل أن عندك فريق عمل وكل شخص فيه يمسك بطاقة مكتوب عليها “أنا”. وكل واحد في الفريق بيقول “أنا” عشان يتكلم عن نفسه. بس، لو ما كان فيه طريقة عشان تفرق بين “أنا” و"أنا"، راح يصير الموضوع فوضوي، صح؟
هنا يجي دور self، المنقذ اللي يخلي كل شيء واضح!
“أنا القائد، يا شباب!”
self هو طريقة بايثون في إخبار الكائنات (objects): “هذا اللي تكلمون عنه هو أنت بالضبط!”. يعني لما تستدعي method داخل class، أول حاجة تعرّفها هي self، وبهذا الشكل، الكائن يعرف أنه المقصود!
مثال بسيط:
class قطة:
def __init__(self, اسم):
self.اسم = اسم
def ميو(self):
return f"{self.اسم} تقول ميو!"
هنا self يقول: “أنا الكائن اللي تتكلمون عنه!”.
“أرفع يدي وأقول: أنا!”
لما الكائن يعرف نفسه باستخدام self، يقدر بسهولة يتواصل مع باقي الكائنات والmethods. إنه الصديق اللي دايم يوضح الأمور.
English
:
Imagine you have a team, and everyone’s wearing a badge that says “I”. Now, if everyone just says “I” without any context, it’s going to get confusing pretty quickly, right?
That’s where self steps in to save the day!
“I’m the boss here, folks!”
self is Python’s way of telling objects, “Hey, this is YOU we’re talking about!”. So when you call a method inside a class, the first thing you pass is self, and now the object knows exactly who it is!
Simple example:
class Cat:
def __init__(self, name):
self.name = name
def meow(self):
return f"{self.name} says Meow!"
Here, self says, “I’m the one you’re referring to!”
“Raise my hand and say: I!”
When the object identifies itself using self, it can easily interact with other objects and methods. It’s that friend who always keeps things clear.
self هو التذكير الذاتي اللي يخلي الكائنات في بايثون عارفة نفسها ومترابطة. ما نقدر نعيش بدون هذا “أنا” الصغير!