பாடம் 4 / 7 · Classes-ம் Objects-ம் · படிக்க 3 min · புதுப்பிக்கப்பட்டது
Polymorphism
ஒரே call, பல வகை objects — object என்னன்னு இல்ல, அது என்ன செய்யும்னு Python ஏன் பார்க்குது.
Polymorphism-ன்னா வேற வேற types ஒரே call-க்கு அதது வழியில பதில் சொல்றது. உங்க loop-க்கு அது எந்த வகை object-ன்னு தெரிய வேண்டியதில்ல — கேட்டதை அது செய்யுமான்னு மட்டும் போதும்.
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return round(3.14159 * self.r ** 2, 2)
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
for shape in [Circle(1), Rectangle(3, 4), Circle(2)]:
print(type(shape).__name__, shape.area())
Circle 3.14
Rectangle 12
Circle 12.57
Circle-க்கும் Rectangle-க்கும் பொதுவான parent இல்ல, ஆனாலும் ரெண்டுக்கும் area() method இருக்கிறதால loop ரெண்டையும் ஒரே மாதிரி நடத்துது. இதை Python duck typing-ன்னு சொல்லும்: வாத்து மாதிரி நடந்து, வாத்து மாதிரி கத்தினா, அதை வாத்தா நடத்து.
print(len("hello"), len([1, 2]), len({"a": 1}))
print("ab" * 2, [0] * 3)
5 2 1
abab [0, 0, 0]
முதல் பாடங்கள்ல இருந்தே polymorphism use பண்ணிட்டு இருக்கீங்க: len() strings, lists, dictionaries எல்லாத்துலயும் வேலை செய்யும்; * numbers-க்கு ஒரு அர்த்தம், strings, lists-க்கு இன்னொரு அர்த்தம்.
பொதுவான parent வழியா
class Animal:
def speak(self):
raise NotImplementedError("each animal must speak")
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for animal in [Dog(), Cat()]:
print(animal.speak())
Woof
Meow
Note
Parent-ஓட speak NotImplementedError raise பண்றது, ஒவ்வொரு child-ம் காப்பாத்த வேண்டிய வாக்குறுதியை பதிவு பண்ணுது. Override பண்ண மறந்த child, முதல் தடவை speak பண்ண சொல்லும்போதே சத்தமா தோல்வியடையும்.
ஒரு function list-ல இருக்கிற எல்லாத்து மேலயும் item.area() கூப்பிடுது. ஒவ்வொரு item-க்கும் என்ன வேணும்?
இப்போ இதை செஞ்சு பாருங்க
area()-ஓடTriangleclass சேர்த்து, loop-ஐ மாத்தாமலே shapes-ல சேருங்க.- UPI, Card, Cash payments-க்கு ஒவ்வொண்ணுக்கும்
pay(amount)-ஓட classes எழுதி, கலந்த payments list-ஐ process பண்ணுங்க.
Create a free account to save your progress, or sign in.