---
title: Python Polymorphism
description: "> ## Python Polymorphism – Python Полиморфизм > > > > The word “polymorphism” means “many forms”, and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes. > > > >…"
url: "https://apprentice.mn/docs/python-polymorphism/"
updated: "2024-07-30"
category: Python
---

# Python Polymorphism

> ## Python Polymorphism – Python Полиморфизм
>
>
>
> The word “polymorphism” means “many forms”, and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
>
>
>
> Полиморфизм гэдэг нь “олон хэлбэр” гэсэн утгатай бөгөөд программчлалд адил нэртэй боловч өөр өөр объектыг буюу классуудыг хэрэгжүүлдэг функц, аргачлал, операторуудыг хэлнэ.

## Function Polymorphism – Функцийн Полиморфизм

An example of a Python function that can be used on different objects is the `len()` function.

Python-д функцүүдийг янз бүрийн объектод ашиглах боломжтой. Жишээ нь, `len()` функц.

### String – Тэмдэгт Мөр

For strings `len()` returns the number of characters:

Мөрүүдэд `len()` функц нь тэмдэгтүүдийн тоог буцаана:

 

#### Example – Жишээ

`x = "Hello World!"print(len(x))`

### Tuple – Хослол

For tuples `len()` returns the number of items in the tuple:

Хослолд `len()` нь элементийн тоог буцаана:

#### Example – Жишээ

`mytuple = ("apple", "banana", "cherry")
print(len(mytuple))`

### Dictionary – Лавлах

For dictionaries `len()` returns the number of key/value pairs in the dictionary:

Лавлахад `len()` нь “түлхүүр-утга” хосын тоог буцаана:

#### Example – Жишээ

`thisdict = {  "brand": "Ford",  "model": "Mustang",  "year": 1964}print(len(thisdict))`

## Class Polymorphism – Классын Полиморфизм

Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.

Полиморфизм нь классын аргачлалууд дээр өргөн хэрэглэгддэг. Үүнтэй адил аргачлал бүхий хэд хэдэн ангитай байж болно.

For example, say we have three classes: `Car`, `Boat`, and `Plane`, and they all have a method called `move()`:

`Car`, `Boat`, `Plane` гэсэн гурван анги байг, тэдэнд бүгдэнд `move()` арга байгаа гэж төсөөлөөд үзье.

#### Example – Жишээ

Different classes with the same method:

Өөр классууд адил аргатай байх: 

`class Car:  def __init__(self, brand, model):    self.brand = brand    self.model = model  def move(self):    print("Drive!")class Boat:  def __init__(self, brand, model):    self.brand = brand    self.model = model  def move(self):    print("Sail!")class Plane:  def __init__(self, brand, model):    self.brand = brand    self.model = model  def move(self):    print("Fly!")car1 = Car("Ford", "Mustang")       #Create a Car classboat1 = Boat("Ibiza", "Touring 20") #Create a Boat classplane1 = Plane("Boeing", "747")     #Create a Plane classfor x in (car1, boat1, plane1):x.move()`

Look at the for loop at the end. Because of polymorphism we can execute the same method for all three classes.

Эцсийн **for** давталтаас хараарай. Учир нь полиморфизмын ачаар бид гурван классын аль алинд нь адилхан аргыг хэрэгжүүлэх боломжтой.

## Inheritance Class Polymorphism – Удамшсан классын Полиморфизм

What about classes with child classes with the same name? Can we use polymorphism there?

Тухайн класс хүүхэд класстай бол функцүүдийн нэрийг үргэлжлүүлэн ашиглаж болох уу?

Yes. If we use the example above and make a parent class called `Vehicle`, and make `Car`, `Boat`, `Plane` child classes of `Vehicle`, the child classes inherits the `Vehicle` methods, but can override them:

Тийм ээ. Жишээ нь, `Vehicle` нэртэй эцэг класс үүсгэн `Car`, `Boat`, `Plane` зэрэг хүүхэд классыг үүсгэнэ гэж үзье. Хүүхэд класс нь эцэг классын арга, шинж чанарыг удамшиж авдаг ч хэрэглэхгүй байж болно:

#### Example – Жишээ

Create a class called `Vehicle` and make `Car`, `Boat`, `Plane` child classes of `Vehicle`:

`Vehicle` нэртэй класс үүсгээд, `Car`, `Boat`, `Plane` ангиудыг `Vehicle` классын хүүхэд класс болгон үүсгэ:

`class Vehicle:  def __init__(self, brand, model):    self.brand = brand    self.model = model  def move(self):    print("Move!")class Car(Vehicle):  passclass Boat(Vehicle):  def move(self):    print("Sail!")class Plane(Vehicle):  def move(self):    print("Fly!")car1 = Car("Ford", "Mustang") #Create a Car objectboat1 = Boat("Ibiza", "Touring 20") #Create a Boat objectplane1 = Plane("Boeing", "747") #Create a Plane objectfor x in (car1, boat1, plane1):  print(x.brand)  print(x.model)  x.move()`

Child classes inherits the properties and methods from the parent class.

Хүүхэд класс нь эцэг классын шинж чанарууд болон аргуудыг удамшуулж авдаг.

In the example above you can see that the `Car` class is empty, but it inherits `brand`, `model`, and `move()` from `Vehicle`.

Дээрх жишээнд `Car` класс хоосон байгаа боловч, `Vehicle`-ээс `brand`, `model`, `move()` зэрэг шинж чанаруудыг удамшуулж авсан байна.

The `Boat` and `Plane` classes also inherit `brand`, `model`, and `move()` from `Vehicle`, but they both override the `move()` method.

`Boat` болон `Plane` классууд мөн адил `Vehicle`-ээс `brand`, `model`, `move()` зэрэг шинж чанаруудыг удамшуулж авсан боловч, хоёулаа `move()` аргыг өөрчлөн ашигласан.

Because of polymorphism we can execute the same method for all classes.

Полиморфизмын ачаар бид бүх классын ижил аргат ажиллах боломжтой.

                   [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-polymorphism%2F&linkname=Python%C2%A0Polymorphism)[https://www.addtoany.com/share](https://www.addtoany.com/share)
