Last active
June 21, 2026 13:10
-
-
Save sunmeat/e3f8cc5699b3e55ac948fe09a5935132 to your computer and use it in GitHub Desktop.
composition example python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PegLeg: # дерев'яна нога | |
| def __init__(self): | |
| self.color = "коричнева" | |
| self.dirty = False | |
| self.length = 14.5 # в дюймах | |
| self.usability = 85 # 0–100 | |
| print(f"{self.__class__.__name__} створено") | |
| def __del__(self): # деструктор для демонстрації знищення об'єкта (частини) | |
| print(f"{self.__class__.__name__} (дерев'яна нога) знищена") | |
| class HandHook: # рука-гачок | |
| def __init__(self): | |
| self.material = "металева" | |
| self.usability = 90 | |
| self.dirty = False | |
| self.can_make_selfie = False | |
| print(f"{self.__class__.__name__} створено") | |
| def __del__(self): | |
| print(f"{self.__class__.__name__} (гачок) знищено") | |
| class BlackEyePatch: # наглазник | |
| def __init__(self): | |
| self.color = "чорний" | |
| self.size = "XXL" | |
| self.elastic = True | |
| self.leather = True | |
| print(f"{self.__class__.__name__} створено") | |
| def __del__(self): | |
| print(f"{self.__class__.__name__} (наглазник) знищено") | |
| class Pirate: | |
| def __init__(self, name): | |
| self.name = name | |
| # композиція: частини створюються всередині класу Pirate | |
| # і належать тільки цьому об'єкту | |
| self.leg = PegLeg() | |
| self.hand = HandHook() | |
| self.patch = BlackEyePatch() | |
| print(f"Пірат {self.name} створений\n") | |
| def capture_ship(self): | |
| print(f"{self.name}: Беремо на абордаж!!!") | |
| def sing_song(self): | |
| print(f"{self.name}: ...Йо-хо-хо, та пляшка рому!") | |
| def __del__(self): # деструктор для демонстрації знищення об'єкта (цілого) | |
| print(f"Пірат {self.name} йде на дно...") | |
| # при деструкції пірата знищуються і всі його частини (композиція) | |
| # деструктори частин викличуться автоматично, бо посилання на них зникають | |
| if __name__ == "__main__": | |
| p = Pirate("Капітан Джек Горобець") | |
| p.capture_ship() | |
| p.sing_song() | |
| # явне видалення об'єкта для демонстрації деструктора | |
| del p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment