# Примеры полиморфизма

### **1. Полиморфизм через переопределение методов (Override)**

Разные классы реализуют один и тот же метод по-своему.

```python
class Dog:
    def speak(self):
        return "Гав"

class Cat:
    def speak(self):
        return "Мяу"

for animal in [Dog(), Cat()]:
    print(animal.speak())
```

**Вывод:**

```
Гав
Мяу
```

📌 Один и тот же вызов `speak()` ведёт себя по-разному для разных объектов.

***

### **2. Полиморфизм через наследование**

Один интерфейс в базовом классе — разные реализации в наследниках.

```python
class Shape:
    def area(self):
        raise NotImplementedError

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14 * self.r * self.r

class Square(Shape):
    def __init__(self, a):
        self.a = a
    def area(self):
        return self.a * self.a

shapes = [Circle(5), Square(4)]
for shape in shapes:
    print(shape.area())
```

***

### **3. Полиморфизм через функции**

Функция не проверяет тип объекта — она просто вызывает метод, который предполагается у него есть (**duck typing**).

```python
def make_it_speak(animal):
    print(animal.speak())

class Parrot:
    def speak(self):
        return "Привет!"

class Frog:
    def speak(self):
        return "Ква"

make_it_speak(Parrot())  # Привет!
make_it_speak(Frog())    # Ква
```

📌 Главное, чтобы у объекта был метод `speak()`, а не его тип.

***

### **4. Полиморфизм в автоматизации тестирования (Page Object Model)**

Разные страницы реализуют один и тот же метод по-разному, но тесты используют его одинаково.

```python
class BasePage:
    def open(self):
        raise NotImplementedError

class LoginPage(BasePage):
    def open(self):
        print("Открываем страницу логина")

class DashboardPage(BasePage):
    def open(self):
        print("Открываем дашборд")

# Тест
def test_navigation(page: BasePage):
    page.open()

# Можно передать любую страницу
test_navigation(LoginPage())
test_navigation(DashboardPage())
```

📌 Тесту не важно, какая страница — он просто вызывает `open()`.

***

### **Коротко суть**

* **Интерфейс одинаковый** (метод с одним именем).
* **Реализация разная** (зависит от объекта).
* В Python это часто реализуется через **наследование** или **duck typing**.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/primery-polimorfizma.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
