Python Nesne Tabanlı Programlama

Bu eğitimde, örnekler yardımıyla Python'da Nesne Tabanlı Programlama (OOP) ve temel kavramını öğreneceksiniz.

Video: Python'da Nesne Tabanlı Programlama

Nesne yönelimli programlama

Python, çok paradigmalı bir programlama dilidir. Farklı programlama yaklaşımlarını destekler.

Bir programlama problemini çözmek için popüler yaklaşımlardan biri, nesneler oluşturmaktır. Bu, Nesne Yönelimli Programlama (OOP) olarak bilinir.

Bir nesnenin iki özelliği vardır:

  • Öznitellikler
  • davranış

Bir örnek alalım:

Bir papağan, aşağıdaki özelliklere sahip olduğu için bir nesne olabilir:

  • nitelik olarak isim, yaş, renk
  • şarkı söylemek, davranış olarak dans etmek

Python'da OOP kavramı, yeniden kullanılabilir kod oluşturmaya odaklanır. Bu kavram aynı zamanda KURU (Kendini Tekrar Etme) olarak da bilinir.

Python'da, OOP kavramı bazı temel ilkeleri takip eder:

Sınıf

Sınıf, nesne için bir plandır.

Sınıfı, etiketleri olan bir papağan çizimi olarak düşünebiliriz. Adı, rengi, boyutu vb. Tüm detayları içerir. Bu açıklamalara dayanarak papağan hakkında çalışabiliriz. Burada papağan bir nesnedir.

Papağan sınıfı için örnek şunlar olabilir:

 sınıf Parrot: geçmek

Burada, classboş bir Parrot sınıfı tanımlamak için anahtar kelimeyi kullanıyoruz . Sınıftan örnekler oluşturuyoruz. Örnek, belirli bir sınıftan oluşturulan belirli bir nesnedir.

Nesne

Bir nesne (örnek), bir sınıfın somutlaştırılmasıdır. Sınıf tanımlandığında, yalnızca nesnenin açıklaması tanımlanır. Bu nedenle, bellek veya depolama tahsis edilmez.

Parrot sınıfının nesnesi için örnek şöyle olabilir:

 obj = Papağan ()

Burada obj bir sınıf nesnesidir Parrot.

Papağanların ayrıntılarına sahip olduğumuzu varsayalım. Şimdi, papağan sınıfını ve nesnelerini nasıl inşa edeceğimizi göstereceğiz.

Örnek 1: Python'da Sınıf ve Nesne Oluşturma

 class Parrot: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Parrot class blu = Parrot("Blu", 10) woo = Parrot("Woo", 15) # access the class attributes print("Blu is a ()".format(blu.__class__.species)) print("Woo is also a ()".format(woo.__class__.species)) # access the instance attributes print("() is () years old".format( blu.name, blu.age)) print("() is () years old".format( woo.name, woo.age))

Çıktı

 Blu bir kuş Woo da bir kuş Blu 10 yaşında Woo 15 yaşında

Yukarıdaki programda Parrot adında bir sınıf oluşturduk. Ardından nitelikleri tanımlarız. Nitelikler bir nesnenin özelliğidir.

Bu öznitelikler __init__, sınıfın yöntemi içinde tanımlanır . Nesne oluşturulur oluşturulmaz ilk çalıştırılan başlatıcı yöntemidir.

Ardından, Parrot sınıfının örneklerini oluşturuyoruz. Burada blu ve woo, yeni nesnelerimize referanslar (değer).

Kullanarak class niteliğine erişebiliriz __class__.species. Sınıf öznitelikleri, bir sınıfın tüm örnekleri için aynıdır. Benzer şekilde, örnek özniteliklerine blu.nameve kullanarak erişiriz blu.age. Ancak, örnek öznitelikleri bir sınıfın her örneği için farklıdır.

Sınıflar ve nesneler hakkında daha fazla bilgi edinmek için Python Sınıfları ve Nesneleri'ne gidin

Yöntemler

Yöntemler, bir sınıfın gövdesi içinde tanımlanan işlevlerdir. Bir nesnenin davranışlarını tanımlamak için kullanılırlar.

Örnek 2: Python'da Yöntem Oluşturma

 class Parrot: # instance attributes def __init__(self, name, age): self.name = name self.age = age # instance method def sing(self, song): return "() sings ()".format(self.name, song) def dance(self): return "() is now dancing".format(self.name) # instantiate the object blu = Parrot("Blu", 10) # call our instance methods print(blu.sing("'Happy'")) print(blu.dance())

Çıktı

 Blu 'Happy' şarkısını söylüyor Blu şimdi dans ediyor

Yukarıdaki programda iki yöntem tanımlıyoruz, yani sing()ve dance(). Bunlara örnek yöntemler denir çünkü bunlar bir örnek nesnede yani blu.

Miras

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python

 # parent class class Bird: def __init__(self): print("Bird is ready") def whoisThis(self): print("Bird") def swim(self): print("Swim faster") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print("Penguin is ready") def whoisThis(self): print("Penguin") def run(self): print("Run faster") peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run()

Output

 Bird is ready Penguin is ready Penguin Swim faster Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class inherits the functions of parent class. We can see this from the swim() method.

Again, the child class modified the behavior of the parent class. We can see this from the whoisThis() method. Furthermore, we extend the functions of the parent class, by creating a new run() method.

Additionally, we use the super() function inside the __init__() method. This allows us to run the __init__() method of the parent class inside the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.

Example 4: Data Encapsulation in Python

 class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: ()".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price c = Computer() c.sell() # change the price c.__maxprice = 1000 c.sell() # using setter function c.setMaxPrice(1000) c.sell()

Output

 Selling Price: 900 Selling Price: 900 Selling Price: 1000

In the above program, we defined a Computer class.

We used __init__() method to store the maximum selling price of Computer. We tried to modify the price. However, we can't change it because Python treats the __maxprice as private attributes.

As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes price as a parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).

Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism.

Example 5: Using Polymorphism in Python

 class Parrot: def fly(self): print("Parrot can fly") def swim(self): print("Parrot can't swim") class Penguin: def fly(self): print("Penguin can't fly") def swim(self): print("Penguin can swim") # common interface def flying_test(bird): bird.fly() #instantiate objects blu = Parrot() peggy = Penguin() # passing the object flying_test(blu) flying_test(peggy)

Output

 Parrot can fly Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have a common fly() method. However, their functions are different.

Polimorfizmi kullanmak için ortak bir arayüz, yani flying_test()herhangi bir nesneyi alan ve nesnenin fly()yöntemini çağıran işlev yarattık . Böylece flying_test()fonksiyondaki blu ve peggy nesnelerini geçtiğimizde etkin bir şekilde çalıştı.

Hatırlanması Gereken Önemli Noktalar:

  • Nesne Yönelimli Programlama, programın verimli olduğu kadar anlaşılmasını da kolaylaştırır.
  • Sınıf paylaşılabilir olduğu için kod yeniden kullanılabilir.
  • Veriler, veri soyutlama ile güvenli ve güvenlidir.
  • Çok biçimlilik, farklı nesneler için aynı arabirime izin verir, böylece programcılar verimli kod yazabilir.

Ilginç makaleler...