Python OOP: Abubuwa da Aji

A cikin Python, abubuwa da azuzuwan mahimman ra'ayoyi ne na shirye-shirye masu dogaro da abu(OOP). Shirye-shiryen da ya dace da abu yana ba ku damar ƙirƙirar abubuwa tare da halayensu da hanyoyin su, suna sa ƙungiyar lambobi bayyanannu da kiyayewa.

 

Ma'anar Class in Python

  • Don ayyana sabon aji, yi amfani da class kalmar maɓalli, sannan sunan ajin(yawanci farawa da babban harafi).
  • A cikin ajin, zaku iya ayyana sifofi(masu canzawa) da hanyoyin(ayyuka) waɗanda abubuwan aji zasu samu.

 

Ƙirƙirar Abubuwa daga Aji

  • Don ƙirƙirar abu daga aji, yi amfani da ma'anar kalma class_name().
  • Wannan zai fara sabon abu bisa kayyade aji.

 

Misali: Ga misali mai sauƙi na yadda ake ayyana aji da ƙirƙirar abubuwa daga gare ta:

# Define the class Person  
class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def say_hello(self):  
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")  
  
# Create objects(instances) from the class Person  
person1 = Person("John", 30)  
person2 = Person("Alice", 25)  
  
# Call the say_hello method from the objects  
person1.say_hello()   # Output: Hello, my name is John and I am 30 years old.  
person2.say_hello()   # Output: Hello, my name is Alice and I am 25 years old.  

A cikin misalin da ke sama, mun ayyana Person ajin tare da halaye biyu name da age, tare da hanya say_hello(). Sa'an nan kuma, mun ƙirƙiri abubuwa biyu person1 kuma person2 daga cikin Person aji kuma muka kira say_hello() hanyar kowane abu don nuna bayanan su.