如何使用map()映射抽象类子类实例的重写方法?
map() with Overridden Methods from Abstract Class Instances Absolutely! You can use map() to call the overridden Method() on your instance list—your problem is likely how you're passing the method reference to map(). Let me break this down with examples and explanations:
Why Your Initial Attempt Failed
If you tried passing MyAbstractClass.Method directly to map(), you’re telling Python to call the parent class’s abstract (empty) method instead of the overridden version in each subclass. That’s because MyAbstractClass.Method is bound to the parent class, not the individual instances’ subclass implementations.
Correct Ways to Use map()
There are two clean ways to make this work, both leveraging Python’s polymorphism to call the right overridden method:
1. Use a Lambda Function
A lambda lets you explicitly call the method on each instance in the list, which triggers the subclass’s overridden implementation:
from abc import ABC, abstractmethod # Define your abstract class and subclasses class MyAbstractClass(ABC): @abstractmethod def Method(self): pass class ConcreteSubclassA(MyAbstractClass): def Method(self): return "Result from Subclass A" class ConcreteSubclassB(MyAbstractClass): def Method(self): return "Result from Subclass B" # Create your instance list instances = [ConcreteSubclassA(), ConcreteSubclassB()] # Use map() with a lambda results = list(map(lambda instance: instance.Method(), instances)) print(results) # Output: ['Result from Subclass A', 'Result from Subclass B']
2. Use operator.methodcaller (More Concise)
For a cleaner approach without lambda, you can use methodcaller from the operator module. It’s designed exactly for this scenario—calling a named method on each item in an iterable:
from operator import methodcaller # Reusing the same instances list from above results = list(map(methodcaller("Method"), instances)) print(results) # Same output as the lambda approach
Why This Works
Both approaches ensure that we’re calling the Method() bound to each individual instance. Since each instance is a subclass of MyAbstractClass, Python’s method resolution order automatically picks the overridden implementation instead of the parent’s abstract method.
内容的提问来源于stack exchange,提问作者Anton Ovsyannikov

