【问题标题】:Is there a way to check if a variable is an instance of an inner class whose outer class is a certain class?有没有办法检查变量是否是外部类是某个类的内部类的实例?
【发布时间】:2021-12-17 11:40:31
【问题描述】:

示例代码:

class A:
    class B:
        def __init__(self):
            pass

var = A.B()

我需要一个函数,比如说check_if_class_parent(obj, class_type),它将检查var 是否是外部类为A 的内部类的实例,如果我运行check_if_class_parent(var, A),它将返回True

有时类结构可能是这样的:

class A:
    class B:
        def __init__(self):
            pass
        
        class C:
            def __init__(self):
                pass

var = A.B.C()
var_two = A.B()

check_if_class_parent(var, A)check_if_class_parent(var, B)check_if_class_parent(var_two, A) 都会返回 True,但 check_if_class_parent(var, C) 会返回 False

【问题讨论】:

  • 那些是嵌套类,不是子类。

标签: python class parent


【解决方案1】:
  1. 可以将outer 属性添加到内部类中,在这种情况下,只需遍历值类型上的任何outer 属性即可查看是否可以到达A。然而,这确实增加了额外的定义。

  2. 可以从A 开始进行搜索。例如。 (根本不考虑任何卑鄙的循环引用):

def is_type_within(obj, type_):
    if isinstance(obj, type_):
        return True
    for attr in dir(type_):
        if attr.startswith('__'):
            continue
        if is_type_within(obj, getattr(type_, attr)):
            return True
    return False

【讨论】:

  • 关于是否包含 A 或仅包含内部类的问题有点不一致,因此可能必须更改第一次检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 2013-09-20
  • 2011-03-26
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
相关资源
最近更新 更多