Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active June 21, 2026 10:42
Show Gist options
  • Select an option

  • Save sunmeat/54c9950b7f4acec898f117856100ebae to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/54c9950b7f4acec898f117856100ebae to your computer and use it in GitHub Desktop.
як виглядає типовий клас в пайтон
from dataclasses import dataclass, field
from datetime import date
from enum import Enum
from random import randint
from typing import List
class EyesColor(Enum):
YELLOW = "Yellow"
BLACK = "Black"
BROWN = "Brown"
GREEN = "Green"
BLUE = "Blue"
DIFFERENT = "Different"
BLIND = "Blind"
@dataclass # @dataclass за замовчуванням додає такі методи: __init__ __repr__ __eq__ (і відповідно __ne__)
# залежно від параметрів декоратора додаються ще:
# order=True (__lt__, __le__, __gt__, __ge__)
# frozen=True (__hash__)
# https://www.it-notes.wiki/python/what-is-dataclasses/
# https://docs.python.org/3/library/dataclasses.html
# https://habr.com/ru/articles/415829/
class Cat:
# статичні поля КЛАСУ (з типами та значеннями за замовчуванням)
gender: int = 0
nick: str = ""
craziness: int = 0
hungry: int = 50
color: str = ""
paws: int = 4
lives: int = 9
has_tail: bool = True
has_fur: bool = True
eyes_color: EyesColor = EyesColor.GREEN
birthdate: date = field(default_factory=lambda: date(2026, 1, 1))
favourite_meal: List[str] = field(default_factory=lambda: ["Whiskas", "Milk"])
weight: float = 5000.0 # грами
kind: str = ""
energy: int = 100
is_alive: bool = True
# @dataclass автоматично згенерує конструктор __init__, але його можна перевизначити, якщо потрібно
# згенерується щось на кшталт цього:
# def __init__(self,
# # ось звідки візьмуться атрибути для майбутніх об'єктів
# gender: int = 0,
# nick: str = "",
# craziness: int = 0,
# hungry: int = 50,
# color: str = "",
# paws: int = 4,
# lives: int = 9,
# has_tail: bool = True,
# has_fur: bool = True,
# eyes_color: EyesColor = EyesColor.GREEN,
# birthdate: date = None,
# favourite_meal: List[str] = None,
# weight: float = 5000.0,
# kind: str = "",
# energy: int = 100,
# is_alive: bool = True,
# ) -> None:
# self.gender = gender
# self.nick = nick
# self.craziness = craziness
# self.hungry = hungry
# self.color = color
# self.paws = paws
# self.lives = lives
# self.has_tail = has_tail
# self.has_fur = has_fur
# self.eyes_color = eyes_color
# if birthdate is None:
# self.birthdate = date(2026, 1, 1)
# else:
# self.birthdate = birthdate
# if favourite_meal is None:
# self.favourite_meal = ["Whiskas", "Milk"]
# else:
# self.favourite_meal = favourite_meal
# self.weight = weight
# self.kind = kind
# self.energy = energy
# self.is_alive = is_alive
# методи
def play(self) -> None:
if self.paws <= 0:
print("В котика нема лапок, він не може гратися!")
return
if self.hungry == 100:
print("Кіт голодний!")
return
if self.energy < 20:
print("Кіт втомився...")
return
if not self.is_alive:
print("Котик помер :(")
return
self.energy -= 10
self.craziness += randint(-5, 5)
self.hungry += randint(0, 10)
self.weight -= randint(0, 1000)
def sleep(self) -> None:
self.hungry = 100
self.energy = 100
def eat(self, meal: str) -> None:
if meal in self.favourite_meal:
self.hungry = 0
self.energy = 100
self.craziness -= 10
self.weight += 1000
self.make_sound()
return
# не улюблена їжа
self.hungry -= 10
self.energy += 10
def make_sound(self) -> None:
print("Няв-няв!")
def print_info(self) -> None:
print("================================")
print(f"Кличка: {self.nick}")
print(f"Характер: {self.craziness}")
print(f"Голодний: {self.hungry}")
print(f"Лапки: {self.paws}")
print(f"Життів: {self.lives}")
print(f"Вага: {self.weight:.0f}g")
print(f"Егенрійність: {self.energy}")
print("================================")
def set_paws(self, value: int) -> None:
if value < 0 or value > 4:
value = 4
self.paws = value
#############################################################################
if __name__ == "__main__":
cat1 = Cat(nick="Локі", hungry=30, craziness=15)
cat1.gender = 1
cat1.print_info()
cat1.play()
cat1.eat("Whiskas")
cat1.print_info()
cat2 = Cat(nick="Фрея", hungry=40, craziness=20)
cat2.gender = 0
cat2.print_info()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment