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: CarBoat, 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 class
boat1 = Boat("Ibiza""Touring 20"#Create a Boat class
plane1 = Plane("Boeing""747")     #Create a Plane class

for 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 CarBoatPlane 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 CarBoatPlane 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):
  pass
class Boat(Vehicle):
  def move(self):
    print("Sail!")
class Plane(Vehicle):
  def move(self):
    print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car object
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object
for 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 brandmodel, and move() from Vehicle.

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

The Boat and Plane classes also inherit brandmodel, 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.

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

Powered by BetterDocs

Leave a Reply