You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何扩展列表以包含所有父类的属性值?

How to Combine Class Variables from All Parent Classes

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 list to our final list. Since First's list is empty, it doesn't affect the output.
  • This approach is flexible too—if you add more subclasses later, their list variables 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:28:21