如何知道哪个基类向子类obj添加了特定属性

2024-10-02 16:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个项目,它包含来自不同文件中几个模块的类的长层次结构。你知道吗

我想知道继承链中类C什么时候得到了属性A (然后我可以得到定义了C的模块M并检查代码)

考虑下面的代码示例,假设除GrandChildOf1ChildOf2之外的所有类都在其他模块中,是否有命令,例如:attribute_base(o4,'a'),输出:Base1?你知道吗

class SweetDir:
    def __sweet_dir__(self):
        """
        Same as dir, but will omit special attributes
        :return: string
        """
        full_dir = self.__dir__()
        sweet_dir  = []
        for attribute_name in full_dir:

            if not (    attribute_name.startswith('__')
                    and  attribute_name.endswith('__')):
                #not a special attribute
                sweet_dir.append(attribute_name)
        return sweet_dir

class Base1(SweetDir):
    def __init__(self):
        super(Base1,self).__init__()
        self.a = 'a'

class Base2(SweetDir):
    def __init__(self):
        super(Base2,self).__init__()
        self.b = 'b'

class ChildOf1 (Base1):
    def __init__(self):
        super(ChildOf1,self).__init__()
        self.c = 'c'

class GrandChildOf1ChildOf2 (Base2,ChildOf1):
    def __init__(self):
        super(GrandChildOf1ChildOf2,self).__init__()
        self.d = 'd'   


o1 = Base1()
o2 = Base2()
o3 = ChildOf1()
o4 = GrandChildOf1ChildOf2()
print(o1.__sweet_dir__())
print(o2.__sweet_dir__())
print(o3.__sweet_dir__())
print(o4.__sweet_dir__())

输出:

['a']
['b']
['a', 'c']
['a', 'b', 'c', 'd']

Tags: 模块nameselfinitdefdirattributeclass
1条回答
网友
1楼 · 发布于 2024-10-02 16:29:52

我不认为有一个内置的功能,但类似的工作(它需要改进):

def attribute_base(your_class, your_attr):

    for base_class in your_class.__mro__:
        if base_class != your_class:
            tmp_inst = base_class()
            if hasattr(tmp_inst, your_attr):
                return base_class

这将返回类的第一个基类,该基类具有您要查找的属性。这显然不是完美的。如果两个或多个基类具有相同的属性(具有相同的名称),则它可能不会返回获得该属性的实际类,但在您的示例中,它会起作用。 [用AKX注释更新:使用__mro__实际上可以解决这个问题]

[更新:有一种方法不需要实例就可以做到这一点,遵循这个有大量文档记录的答案:list-the-attributes-of-a-class-without-instantiating-an-object]

from inspect import getmembers

def attribute_base(your_class, your_attr):
    for base_class in your_class.__mro__:
        if base_class != your_class:
            members = [member[1].__code__.co_names for member in getmembers(base_class) if '__init__' in member and hasattr(member[1], "__code__")]
            for member in members:
                if your_attr in members:
                    return base_class

getmembers提供类的每个成员,包括我们想要的init方法。我们需要检查它是否真的是一个函数(hasattr(member[1], "__code__")),因为如果没有为类定义__init__函数(如示例中的SweetDir),这将返回一个包装器描述符。我们在稀有的(可能的?)案例有几种__init__方法。你知道吗

相关问题 更多 >