繁体   English   中英

如何返回 inheritance 链中所有 class 的属性?

[英]How can I return the attributes for all class in the inheritance chain?

If you have a class hierarchy and some class attribute is overridden in child class then the user of child class should not care what was the value of this attribute in parent classes.

但这就是我想要实现的目标:

class A:
    _ITEM = "A"

    @classmethod
    def getClassPath(cls):
        ???


class B(A):
    _ITEM = "B"


class C(B):
    _ITEM = "C"


# expected behavior:
A.getClassPath()  # "/A"
B.getClassPath()  # "/A/B"
C.getClassPath()  # "/A/B/C"

我最初的问题有点复杂,但它被简化为:从层次结构中的所有类中获取_ITEM属性并以某种方式组合它们。

我该怎么做? 在我的情况下,没有多个 inheritance。

您可以使用mro (方法解析顺序)访问 inheritance 链中的属性。 简单案例:

class A:
    _ITEM = "A"
    
    @classmethod
    def get_class_path(cls):
        result = cls.mro()[:-1]
        result = [res._ITEM for res in reversed(result)]
        result = "/" + "/".join(result)
        return result

此外,如果您想跳过没有_ITEM的类,您可以使用vars()稍微修改:

class A:
    _ITEM = "attr_A"

    @classmethod
    def get_class_path(cls):
        mro_list = reversed(cls.mro()[:-1])

        result = []
        for obj in mro_list:
            if "_ITEM" in vars(obj):
                result.append(obj._ITEM)

        result = "/" + "/".join(result)
        return result

class B(A):
    # _ITEM = "attr_B"
    pass

class C(B):
    _ITEM = "attr_C"

output:

B.get_class_path() # returns '/attr_A'
C.get_class_path() # returns '/attr_A/attr_C'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM