> For the complete documentation index, see [llms.txt](https://pythonforstarters.solomonmarvel.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pythonforstarters.solomonmarvel.com/object-oriented-programming-in-python/python-class-polymorphism.md).

# Python Class Polymorphism

Polymorphism is the process of using an operator or function in different ways for different data input. In practical terms, polymorphism means that if `class B` inherits from `class A`, it doesn't have to inherit everything about class A; it can do some of the things that class A does differently.

```python
# basic_polymorphism.py

a = "alfa"
b = (1, 2, 3, 4)
c = ['o', 'm', 'e', 'g', 'a']

print(a[2])
print(b[1])
print(c[3])
```

Python uses polymorphism extensively in built-in types. Here we use the same indexing operator for three different data types.

Polymorphism is mostly used when dealing with inheritance.

```python
# polymorphism.py

class Animal:
   def __init__(self, name=''):
      self.name = name

   def talk(self):
      pass

class Cat(Animal):
   def talk(self):
      print("Meow!")

class Dog(Animal):
   def talk(self):
      print("Woof!")

a = Animal()
a.talk()

c = Cat("Missy")
c.talk()

d = Dog("Rocky")
d.talk()
```

Here we have two species: a *dog* and a *cat*. Both are *animals*. The `Dog` class and the `Cat` class inherit the `Animal` class. They have a talk method, which gives different output for them.

```bash
$ ./polymorphism.py 

Meow!
Woof!
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://pythonforstarters.solomonmarvel.com/object-oriented-programming-in-python/python-class-polymorphism.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
