Last active
February 13, 2026 16:11
-
-
Save sunmeat/47d54795cc490590891293b1840aeaff to your computer and use it in GitHub Desktop.
приклад на властивості в пайтон
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
| from datetime import date | |
| class Person: | |
| # можна заборонити додавання нових атрибутів на льоту | |
| # __slots__ = ("_name", "_birthday", "_knows_python") # дозволені атрибути | |
| def __init__(self): | |
| self._name = "Микола" | |
| self._birthday = date(1970, 1, 1) | |
| self._knows_python = False | |
| # --- name property --- | |
| @property | |
| def name(self): | |
| return self._name | |
| @name.setter | |
| def name(self, value): | |
| # приклад перевірки: забороняємо ім'я "Олег" | |
| # if value.lower() == "Олег": | |
| # raise ValueError("Неприпустиме ім'я... :)") | |
| self._name = value | |
| # --- birthday property --- | |
| @property | |
| def birthday(self): | |
| return self._birthday | |
| def set_birthday(self, day: int, month: int, year: int): | |
| self._birthday = date(year, month, day) | |
| # --- knows_python property --- | |
| @property | |
| def knows_python(self): | |
| return self._knows_python | |
| @knows_python.setter | |
| def knows_python(self, value: bool): | |
| self._knows_python = value | |
| ######################################################################## | |
| if __name__ == "__main__": | |
| p = Person() | |
| p.name = "Олександр" | |
| p.set_birthday(10, 3, 1989) | |
| p.knows_python = True | |
| print(p.name) | |
| print(p.birthday) | |
| print(p.knows_python) | |
| # створює новий атрибут у конкретного об’єкта | |
| # після цього можна його читати | |
| # це працює лише для конкретного об’єкта, а не для всіх об’єктів класу | |
| p.knows_cpp = True | |
| print(p.knows_cpp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment