PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Polymorphism and Method Overriding in Python (पॉलीमॉर्फिज्म: मेथड ओवरराइडिंग और डक टाइपिंग (Duck Typing)) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: Polymorphism allows a unified interface, method name, or operator to handle objects of distinct types seamlessly at runtime. Python achieves runtime polymorphism through dynamic method overriding in inheritance, duck typing across unrelated classes, and dunder-based operator overloading.
अध्याय सार: पॉलीमॉर्फिज्म (बहुरूपता) एक ही इंटरफेस, मेथड नाम या ऑपरेटर को विभिन्न प्रकार के ऑब्जेक्ट्स पर अलग-अलग व्यवहार के साथ कार्य करने की क्षमता देता है। पायथन में इसे मुख्यतः मेथड ओवरराइडिंग, डक टाइपिंग (Duck Typing) और डंडर मेथड्स द्वारा ऑपरेटर ओवरलोडिंग से लागू किया जाता है।
Polymorphism and Method Overriding in Python: Detailed Notes & Architecture (पॉलीमॉर्फिज्म: मेथड ओवरराइडिंग और डक टाइपिंग (Duck Typing))
1. Method Overriding and Runtime Dynamic Dispatch (मेथड ओवरराइडिंग और डायनामिक डिस्पैच)
[EN] Method overriding occurs when a subclass redefines a method already present in its parent class to provide specialized behavior. Because Python performs dynamic late binding at runtime, calling obj.area() automatically invokes the subclass implementation without requiring C++-style virtual keywords. When extending rather than replacing parent logic, the subclass calls super().area() inside the overridden method.
[HI] मेथड ओवरराइडिंग तब होती है जब कोई सबक्लास अपनी पेरेंट क्लास में पहले से मौजूद मेथड को नए व्यवहार के साथ पुनः परिभाषित करती है। चूंकि पायथन रनटाइम पर डायनामिक लेट बाइंडिंग करता है, इसलिए C++ के virtual कीवर्ड के बिना ही obj.area() स्वतः सबक्लास वाला मेथड चलाता है। पेरेंट की कार्यप्रणाली को पूरी तरह हटाने के बजाय आगे बढ़ाने के लिए ओवरराइडिंग मेथड के अंदर super().area() कॉल किया जाता है।
2. Duck Typing Philosophy and Structural Protocols (डक टाइपिंग (Duck Typing) और प्रोटोकॉल डिज़ाइन)
[EN] Coined from the adage 'If it walks like a duck and quacks like a duck, it must be a duck,' duck typing evaluates an object's suitability by the presence of required methods or attributes at runtime rather than its inheritance lineage. Unrelated classes like Square(Shape) and standalone Circle work identically in a loop calling obj.area(). For static type checking, Python 3.8+ formalized structural subtyping through typing.Protocol (PEP 544).
[HI] 'यदि कोई वस्तु बत्तख की तरह चलती और बोलती है, तो वह बत्तख है'—इसी सिद्धांत पर आधारित डक टाइपिंग में ऑब्जेक्ट की क्लास या इनहेरिटेंस देखने के बजाय यह देखा जाता है कि उसमें आवश्यक मेथड मौजूद है या नहीं। जैसे आपस में असंबद्ध Square और Circle दोनों में .area() होने पर एक ही लूप दोनों पर काम कर सकता है। स्टैटिक टाइप चेकिंग के लिए पायथन 3.8+ में typing.Protocol (PEP 544) जोड़ा गया है।
3. Method Overloading vs Dunder Operator Overloading (मेथड ओवरलोडिंग बनाम डंडर ऑपरेटर ओवरलोडिंग)
[EN] Unlike Java or C++, Python does NOT support traditional compile-time method overloading based on parameter count or types; defining two same-named methods in one class overwrites the first. Developers achieve similar flexibility via default arguments, *args/**kwargs, or @functools.singledispatch. Meanwhile, operator overloading customizes operators like +, ==, <, and [] by implementing special dunder methods such as __add__, __eq__, __lt__, and __getitem__.
[HI] जावा या C++ के विपरीत, पायथन में पैरामीटर संख्या या डेटा टाइप के आधार पर पारंपरिक मेथड ओवरलोडिंग नहीं होती; एक ही क्लास में एक नाम के दो मेथड लिखने पर बाद वाला पहले को ओवरराइट कर देता है। इसके विकल्प के रूप में डिफ़ॉल्ट आर्ग्यूमेंट, *args/**kwargs या @functools.singledispatch उपयोग किए जाते हैं। वहीं +, == या [] जैसे ऑपरेटर ओवरलोड करने के लिए __add__, __eq__ और __getitem__ जैसे डंडर मेथड्स लिखे जाते हैं।
4. Polymorphic Built-ins and Abstract Base Classes (abc) (पॉलीमॉर्फिक बिल्ट-इन फंक्शंस और abc मॉड्यूल)
[EN] Standard functions like len(), sorted(), and str() are polymorphic because they delegate to __len__(), __lt__(), and __str__() regardless of object type. When a strict contract is required across subclasses, inheriting from abc.ABC and decorating mandatory methods with @abstractmethod ensures Python raises TypeError if someone tries to instantiate a concrete subclass that forgot to override them.
[HI] len(), sorted() और str() जैसे बिल्ट-इन फंक्शंस स्वयं पॉलीमॉर्फिक हैं क्योंकि वे किसी भी ऑब्जेक्ट के __len__(), __lt__() और __str__() मेथड को कॉल करते हैं। यदि सबक्लासेस के लिए अनिवार्य नियम बनाना हो, तो abc.ABC से इनहेरिट करके @abstractmethod डेकोरेटर लगाया जाता है, जिससे उन मेथड्स को ओवरराइड किए बिना सबक्लास का ऑब्जेक्ट बनाने पर TypeError आ जाता है।
Syntax, Formula & Technical Example (Polymorphism and Method Overriding in Python)
class Shape:
def area(self): return 0
class Square(Shape):
def __init__(self, s): self.s = s
def area(self): return self.s * self.s
class Circle:
def __init__(self, r): self.r = r
def area(self): return round(3.14 * self.r * self.r, 2)
for obj in (Square(4), Circle(2)):
print(obj.area())
Polymorphism and Method Overriding in Python Quick Reference & Comparison Table
| Polymorphism Form | Python Mechanism | Exam Key Point |
|---|---|---|
| Method Overriding | Child redefines inherited parent method | Resolved dynamically via runtime dispatch |
| Duck Typing | Relies on method presence, not base class | Follows EAFP; no common parent needed |
| Operator Overloading | Dunder methods (__add__, __eq__, __len__) | Customizes built-in operators on objects |
| Abstract Base Class | abc.ABC paired with @abstractmethod | Prevents instantiation until overridden |
Polymorphism and Method Overriding in Python Top 20 Bilingual MCQs with Answers
Q1. What is the core principle behind Duck Typing in Python?
(पायथन में डक टाइपिंग (Duck Typing) का मूल सिद्धांत क्या है?)
(A) Objects must inherit from a shared interface named DuckBase
(B) An object's compatibility depends on having the required methods/attributes rather than its class type
(C) Variables must be statically typed before calling methods
(D) Only built-in types support polymorphic functions
Correct Answer: (B)
[EN] Duck typing checks behavior (whether obj.area() exists) at runtime instead of inspecting isinstance(obj, Parent).
[HI] डक टाइपिंग में ऑब्जेक्ट की क्लास देखने के बजाय यह देखा जाता है कि उसमें आवश्यक मेथड या व्यवहार मौजूद है या नहीं।
Q2. What output does the Shape/Square/Circle snippet above produce?
(ऊपर दिए गए Shape/Square/Circle कोड को चलाने पर क्या आउटपुट आएगा?)
(A) 16 followed by 12.56
(B) 16 followed by 6.28
(C) TypeError because Circle does not inherit from Shape
(D) 0 followed by 12.56
Correct Answer: (A)
[EN] Square overrides Shape.area() returning 16, and unrelated Circle works via duck typing returning 12.56.
[HI] Square ओवरराइडिंग से 16 देता है और Shape से असंबद्ध होते हुए भी Circle डक टाइपिंग के कारण 12.56 प्रिंट करता है।
Q3. Does Python support traditional Java/C++-style compile-time method overloading inside a single class?
(क्या पायथन एक ही क्लास के भीतर जावा/C++ जैसी पारंपरिक मेथड ओवरलोडिंग को सपोर्ट करता है?)
(A) Yes; Python matches parameter count automatically at compile time
(B) No; redefining a method with the same name overwrites the previous definition
(C) Yes; whenever type hints differ on parameters
(D) Only for @staticmethod functions
Correct Answer: (B)
[EN] A class dictionary holds one entry per method name, so a second def foo(...) replaces the earlier one.
[HI] क्लास नेमस्पेस में एक नाम की केवल एक ही प्रविष्टि रह सकती है, अतः नया मेथड पुराने को ओवरराइट कर देता है।
Q4. Which dunder method must a custom class implement to overload the + (addition) operator?
(कस्टम क्लास में + (जोड़) ऑपरेटर को ओवरलोड करने के लिए किस डंडर मेथड को लागू करना होता है?)
(A) __concat__
(B) __plus__
(C) __add__
(D) __sum__
Correct Answer: (C)
[EN] Evaluating a + b triggers a.__add__(b) (and falls back to b.__radd__(a) if NotImplemented).
[HI] a + b चलाने पर पायथन a.__add__(b) मेथड को कॉल करता है।
Q5. What happens if you try to instantiate a subclass of abc.ABC that fails to override an @abstractmethod?
(यदि abc.ABC की कोई सबक्लास अपने पेरेंट के @abstractmethod को ओवरराइड किए बिना ऑब्जेक्ट बनाने की कोशिश करे तो क्या होगा?)
(A) TypeError: Can't instantiate abstract class
(B) AttributeError when the class is imported
(C) SyntaxError at class definition
(D) The abstract method returns None silently
Correct Answer: (A)
[EN] ABCMeta blocks instantiation with TypeError as long as __abstractmethods__ is non-empty.
[HI] जब तक सभी एब्स्ट्रैक्ट मेथड ओवरराइड नहीं हो जाते, abc.ABC उस सबक्लास का ऑब्जेक्ट बनाने पर TypeError देता है।
Q6. Which dunder method enables built-in len(obj) to work polymorphically on a user-defined collection?
(कौन-सा डंडर मेथड यूजर-डिफाइंड ऑब्जेक्ट पर बिल्ट-इन len(obj) फंक्शन को काम करने योग्य बनाता है?)
(A) __size__
(B) __count__
(C) __length__
(D) __len__
Correct Answer: (D)
[EN] The built-in len() function calls obj.__len__() and validates that it returns a non-negative integer.
[HI] बिल्ट-इन len(obj) फंक्शन अंदरूनी तौर पर obj.__len__() को कॉल करता है।
Q7. Which decorator in the functools module implements single-argument function overloading by type in Python?
(पायथन के functools मॉड्यूल में कौन-सा डेकोरेटर पहले आर्ग्यूमेंट के डेटा टाइप के आधार पर फंक्शन ओवरलोडिंग प्रदान करता है?)
(A) @polymorph
(B) @overloadmethod
(C) @multitype
(D) @singledispatch
Correct Answer: (D)
[EN] @functools.singledispatch turns a function into a generic function dispatching on the type of its first argument.
[HI] @functools.singledispatch पहले आर्ग्यूमेंट के टाइप के अनुसार अलग-अलग फंक्शन इम्प्लीमेंटेशन चलाता है।
Q8. How can an overriding method in a child class invoke the parent's overridden version of the same method?
(चाइल्ड क्लास में ओवरराइड किए गए मेथड के भीतर से पेरेंट क्लास के मूल मेथड को कैसे कॉल किया जा सकता है?)
(A) super().method_name()
(B) base.method_name()
(C) self.parent.method_name()
(D) override.method_name()
Correct Answer: (A)
[EN] super().method_name() delegates along the MRO to execute the parent implementation before or after child logic.
[HI] super().method_name() का उपयोग करके ओवरराइड किए गए पेरेंट मेथड को भी चलाया जा सकता है।
Q9. Which Python module (added in Python 3.8, PEP 544) formalizes static duck typing for type checkers?
(पायथन 3.8 (PEP 544) में टाइप चेकर्स के लिए स्टैटिक डक टाइपिंग (structural subtyping) किस क्लास द्वारा जोड़ी गई?)
(A) inspect.Contract
(B) abc.Duck
(C) typing.Protocol
(D) types.Interface
Correct Answer: (C)
[EN] Subclassing typing.Protocol lets mypy and pyright verify structural methods without runtime inheritance.
[HI] typing.Protocol बिना इनहेरिटेंस के केवल मेथड हस्ताक्षर के आधार पर स्टैटिक डक टाइपिंग की जांच करता है।
Q10. Which dunder method is invoked when comparing two objects with the == operator?
(दो ऑब्जेक्ट्स के बीच == ऑपरेटर से तुलना करने पर कौन-सा डंडर मेथड चलता है?)
(A) __cmp__
(B) __same__
(C) __match__
(D) __eq__
Correct Answer: (D)
[EN] a == b invokes a.__eq__(b); Python 3 removed Python 2's unified __cmp__ hook.
[HI] पायथन 3 में a == b की तुलना करने पर a.__eq__(b) मेथड कॉल होता है।
Q11. Which two-word acronym describes the Pythonic exception-based style closely paired with duck typing?
(डक टाइपिंग के साथ प्रयुक्त होने वाली पायथन की प्रसिद्ध कोडिंग शैली को किस संक्षिप्त नाम से जाना जाता है?)
(A) RAII (Resource Acquisition Is Initialization)
(B) EAFP (Easier to Ask for Forgiveness than Permission)
(C) LBYL (Look Before You Leap strictly)
(D) FIFO (First In First Out)
Correct Answer: (B)
[EN] EAFP tries using an operation directly and catches AttributeError/TypeError if unsupported, avoiding rigid isinstance checks.
[HI] EAFP (Easier to Ask for Forgiveness than Permission) में पहले टाइप जांचने के बजाय सीधे मेथड चलाकर त्रुटि पकड़ी जाती है।
Q12. Why is Python's built-in + operator itself considered polymorphic?
(पायथन का बिल्ट-इन + ऑपरेटर स्वयं पॉलीमॉर्फिक क्यों कहलाता है?)
(A) It automatically converts strings into integers before adding
(B) It works exclusively on numeric subclasses
(C) It creates a separate thread for each operand
(D) It adds numbers (2 + 3 -> 5), concatenates strings ('a' + 'b' -> 'ab'), and joins lists ([1] + [2])
Correct Answer: (D)
[EN] A single + symbol exhibits distinct behaviors depending on the __add__ method of its operand objects.
[HI] एक ही + ऑपरेटर संख्याओं को जोड़ता है और स्ट्रिंग्स या लिस्ट्स को आपस में मिलाता (concatenate) है।
Q13. Which statement about __str__ and __repr__ polymorphism in Python is accurate?
(पायथन में __str__ और __repr__ के बारे में कौन-सा कथन सही है?)
(A) print(obj) ignores __str__ completely
(B) print(obj) prefers __str__ and falls back to __repr__ if __str__ is undefined
(C) __repr__ is called only by len()
(D) __str__ must return an integer code
Correct Answer: (B)
[EN] str(obj) and print(obj) invoke __str__ when defined, defaulting to __repr__ as the universal fallback.
[HI] print(obj) पहले __str__ खोजता है और यदि वह न हो तो __repr__ का उपयोग करता है।
Q14. Which keyword is required in Python to mark a parent method as overridable (virtual) by subclasses?
(पायथन में किसी पेरेंट मेथड को सबक्लास द्वारा ओवरराइड करने योग्य (virtual) बनाने के लिए किस कीवर्ड की आवश्यकता होती है?)
(A) abstract
(B) None; all methods in Python are dynamically dispatched (virtual) by default
(C) override
(D) virtual
Correct Answer: (B)
[EN] Unlike C++ or C#, Python dispatches every method dynamically at runtime with no special keyword required.
[HI] C++ या C# के विपरीत पायथन में किसी विशेष कीवर्ड की आवश्यकता नहीं होती; सभी मेथड डिफ़ॉल्ट रूप से डायनामिक (virtual) होते हैं।
Q15. Which statement about polymorphism and method overriding in Python is NOT true?
(पायथन में पॉलीमॉर्फिज्म और मेथड ओवरराइडिंग के बारे में निम्नलिखित में से कौन-सा कथन असत्य है?)
(A) Operator overloading is implemented using special dunder methods
(B) Subclasses can extend parent methods via super()
(C) Method overriding requires the child and parent methods to be marked with @override to compile
(D) Duck typing allows unrelated classes with matching methods to be used interchangeably
Correct Answer: (C)
[EN] Python requires no decorator for overriding (typing.override in 3.12 is optional for static checkers only).
[HI] पायथन में मेथड ओवरराइड करने के लिए किसी डेकोरेटर या कीवर्ड की अनिवार्यता नहीं होती।
Q16. What happens when a + b is evaluated if a.__add__(b) returns NotImplemented?
(यदि a + b चलाते समय a.__add__(b) द्वारा NotImplemented लौटाया जाए तो पायथन क्या करता है?)
(A) Python converts both operands to str
(B) Python tries calling b.__radd__(a) before raising TypeError
(C) Python prints the string 'NotImplemented'
(D) Python immediately returns None
Correct Answer: (B)
[EN] Returning NotImplemented signals Python to delegate to the right-hand operand's reflected method __radd__.
[HI] NotImplemented लौटने पर पायथन दाएँ ऑपरेंड पर रिवर्स मेथड b.__radd__(a) चलाने का प्रयास करता है।
Q17. Within Polymorphism and Method Overriding in Python, which polymorphism form directly maps to: "Child redefines inherited parent method"?
(Polymorphism and Method Overriding in Python में कौन सा Polymorphism Form सीधे "Child redefines inherited parent method" से संबंधित है?)
(A) Operator Overloading
(B) Method Overriding
(C) Abstract Base Class
(D) Duck Typing
Correct Answer: (B)
[EN] In Polymorphism and Method Overriding in Python, 'Method Overriding' handles 'Child redefines inherited parent method' (Resolved dynamically via runtime dispatch).
[HI] Polymorphism and Method Overriding in Python में 'Method Overriding' का कार्य/विवरण 'Child redefines inherited parent method' (Resolved dynamically via runtime dispatch) है।
Q18. Which option accurately describes 'Duck Typing' in Polymorphism and Method Overriding in Python?
(Polymorphism and Method Overriding in Python के संदर्भ में 'Duck Typing' की सही विशेषता कौन सी है?)
(A) Dunder methods (__add__, __eq__, __len__)
(B) Child redefines inherited parent method
(C) Relies on method presence, not base class
(D) abc.ABC paired with @abstractmethod
Correct Answer: (C)
[EN] 'Duck Typing' provides 'Relies on method presence, not base class' — key point: Follows EAFP; no common parent needed.
[HI] 'Duck Typing' का मुख्य विवरण 'Relies on method presence, not base class' है (Follows EAFP; no common parent needed)।
Q19. In Polymorphism and Method Overriding in Python, identify the correct parameter for the specification: "Dunder methods (__add__, __eq__, __len__)".
(Polymorphism and Method Overriding in Python में "Dunder methods (__add__, __eq__, __len__)" विवरण किस विकल्प के लिए सही है?)
(A) Duck Typing
(B) Method Overriding
(C) Abstract Base Class
(D) Operator Overloading
Correct Answer: (D)
[EN] 'Operator Overloading' corresponds to 'Dunder methods (__add__, __eq__, __len__)' (Customizes built-in operators on objects).
[HI] 'Operator Overloading' का संबंध 'Dunder methods (__add__, __eq__, __len__)' (Customizes built-in operators on objects) से है।
Q20. Considering Polymorphism and Method Overriding in Python, what key behavior defines 'Abstract Base Class'?
(Polymorphism and Method Overriding in Python में 'Abstract Base Class' की मुख्य भूमिका या मान क्या है?)
(A) Child redefines inherited parent method
(B) abc.ABC paired with @abstractmethod
(C) Relies on method presence, not base class
(D) Dunder methods (__add__, __eq__, __len__)
Correct Answer: (B)
[EN] 'Abstract Base Class' represents 'abc.ABC paired with @abstractmethod' (Prevents instantiation until overridden).
[HI] 'Abstract Base Class' का अर्थ/मान 'abc.ABC paired with @abstractmethod' है (Prevents instantiation until overridden)।
Polymorphism and Method Overriding in Python — Exam FAQs
Q1: What is the difference between method overriding and method overloading?
मेथड ओवरराइडिंग और मेथड ओवरलोडिंग में क्या अंतर है?
[EN] Method overriding redefines an inherited parent method inside a child class (fully supported in Python), whereas method overloading defines multiple same-named methods with different parameter lists in one class (not natively supported in Python; simulated via defaults or @singledispatch).
[HI] मेथड ओवरराइडिंग में चाइल्ड क्लास पेरेंट के मेथड को नया रूप देती है (पायथन में पूर्णतः समर्थित), जबकि मेथड ओवरलोडिंग एक ही क्लास में अलग पैरामीटर के साथ समान नाम के कई मेथड बनाना है (पायथन इसे डिफ़ॉल्ट रूप से सपोर्ट नहीं करता)।
Q2: When should I prefer abc.ABC over pure duck typing?
शुद्ध डक टाइपिंग की तुलना में abc.ABC का उपयोग कब करना चाहिए?
[EN] Use abc.ABC when building large frameworks or plugin architectures where missing required methods should fail immediately at object instantiation rather than later during execution.
[HI] जब बड़ा फ्रेमवर्क या प्लगइन सिस्टम बनाया जा रहा हो और यह सुनिश्चित करना हो कि अधूरी सबक्लास का ऑब्जेक्ट बनते समय ही त्रुटि पकड़ी जाए, तब abc.ABC उपयोग करें।
Q3: Why is Python polymorphism closely linked to dynamic typing?
पायथन में पॉलीमॉर्फिज्म डायनामिक टाइपिंग से गहराई से क्यों जुड़ा है?
[EN] Because variables have no fixed static type declarations, any function can accept objects of arbitrary classes and dispatch methods dynamically based on the object passed at runtime.
[HI] क्योंकि वेरिएबल्स का कोई कठोर स्टैटिक टाइप नहीं होता, इसलिए एक ही फंक्शन रनटाइम पर किसी भी उपयुक्त ऑब्जेक्ट को स्वीकार कर उस पर सही मेथड चला सकता है।
Post a Comment
Post a Comment