Özet - Soyut sınıflar
- Python kursu
- Orta seviye
- Ders 52/116
- 5 dk
ABC ve Protocol'ü birleştirerek bir ödeme sistemi yazarsın.
Özet - Soyut sınıflar
Bu grupta soyut sınıf (ABC) temellerini, @abstractmethod ile zorunlu metotları, soyut property tanımlamayı, Protocol ile yapısal uyumu ve ABC ile Protocol farkını gördük.
ABC miras zorunlu kılar; soyut metot ve soyut property alt sınıf tarafından doldurulur. Protocol ise miras istemeden yapısal uyum sağlar. Şimdi bunları birleştiren bir örneği yazacağız.
Uygulama Birleşik özet örneği
from abc import ABC, abstractmethod ile başla. Shape(ABC) soyut sınıfını tanımla; içinde @property ve @abstractmethod ile def area(self): ve pass olsun. class Rectangle(Shape): alt sınıfını tanımla; def __init__(self, w, h): ve self.w = w, self.h = h yaz. @property ile def area(self): ekleyip return self.w * self.h yaz. En son r = Rectangle(3, 4) ile örnek oluştur ve print(r.area) ile yazdır.
Başlangıç kodu
# Shape soyut sınıfını ve Rectangle alt sınıfını yazÖrnek çözüm
# Shape soyut sınıfını ve Rectangle alt sınıfını yaz
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
r = Rectangle(3, 4)
print(r.area)Beklenen çıktı
12
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Hangi kombinasyon yanlış?
- @property + @abstractmethod üst üste
- ABC + @abstractmethod
- @runtime_checkable + Protocol
- @abstractmethod + Protocol tabanı Doğru cevap
Açıklama: Protocol'de abstractmethod kullanılmaz.
2 Kavramları eşleştir
| Kavram | Anlamı |
|---|---|
ABC |
Miras zorunlu |
@abstractmethod |
Zorunlu metot |
@property + @abstractmethod |
Soyut property |
Protocol |
Yapısal uyum |
3 Rectangle property satırı
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
____
def area(self):
return self.w * self.h
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
Açıklama: Alt sınıf @property ile area'yı doldurur.
4 Soyut sınıf parçalarını eşleştir
| Kavram | Anlamı |
|---|---|
ABC |
Soyut taban |
@abstractmethod |
Zorunlu metot |
@property |
Alt sınıf dolgusu |
r.area |
Hesap çağrısı |