Python中如何扩展列表以包含所有父类的属性值?
Got it, let's fix that get_final_list method so it returns the combined list of all list class variables from your inheritance chain. The key here is leveraging Python's method resolution order (__mro__), which gives us the sequence of classes Python uses to look up attributes.
Updated Code
Here's the modified version of your classes with the working get_final_list method:
class First: list = [] def get_final_list(self): final_list = [] # Traverse the method resolution order of the current instance's class for cls in self.__class__.__mro__: # Only process our custom classes (skip built-in object class) if cls in (First, Second, Third): final_list.extend(cls.list) return final_list class Second(First): list = ['one'] class Third(Second): list = ['two']
Test It Out
If you run this test code:
third_instance = Third() print(third_instance.get_final_list()) # Output: ['one', 'two']
You'll get exactly the result you're expecting!
How It Works
self.__class__.__mro__returns the inheritance sequence for the instance's class:(Third, Second, First, object).- We loop through this sequence, adding the contents of each class's
listto our final list. SinceFirst's list is empty, it doesn't affect the output. - This approach is flexible too—if you add more subclasses later, their
listvariables will automatically be included in the final result.
Even More Generic Version
If you don't want to hardcode the class names (which is better for scalability), you can check if the class explicitly defines the list attribute (instead of inheriting it):
def get_final_list(self): final_list = [] for cls in self.__class__.__mro__: # Check if the class has its own 'list' attribute (not inherited) if 'list' in cls.__dict__: final_list.extend(cls.list) return final_list
This way, any subclass you add later that defines its own list will be included without you having to update the method.
内容的提问来源于stack exchange,提问作者paralosreg

