python - 获取嵌套类的外部类名称 (Python)

标签 python class python-3.x nested

背景

(可能相关,因为可能有更简单的方法来实现我想要的。)

我想构建一种声明式的方式来定义可由静态代码分析工具分析的“方面”。整个概念写下来here .每个方面(例如 Redundancy )都可以递归地具有子方面(例如 Redundancy.Clone )并且每个方面都应具有文档和任意其他属性。用户应该能够选择要分析的方面,我必须以编程方式找出一个方面的内部表示,如果它是用户选择的(即对于给定的类 Redundancy.Clone 我想验证它属于一个给定的字符串 redundancy.clone 但不是 redundancy.unused_import )。

我决定使用这样的类:

class Redundancy(Aspect):
    """
    This meta aspect describes any kind of redundancy in your source code.
    """

    # Can't inherit from Redundancy here because of the recursion
    class Clone(Aspect):
        """
        This redundancy describes a code clone. Code clones are different pieces of
        code in your codebase that are very similar.
        """

        # Stuff...

问题

对于给定的 Aspect我想获取描述字符串的类( Redundancy.Clone -> redundancy.clone )。为此,我必须获取周围模块/类/无论它是什么的名称,检查它是否是一个类(琐碎的)并从中构造一个字符串。

可能的解决方案及其失败原因

我确实尝试查看 dir我的类(class),看看我可以使用的 dunder 方法中是否有任何有用的东西,但除了 repr 之外什么也没有发现。在上面的例子中是 <class 'coalib.bearlib.aspects.Redundancy.Clone'>住在aspects的时候模块。这表明它应该是可能的,但我不知道如何 repr获取此信息,我想避免使用 repr并剥离不需要的东西,因为这是一种 hack。

我无法从外部继承嵌套类,因为它还没有完全定义。我希望它们嵌套以提高可用性,能够 from ... import Redundancy在我的源代码中写 Redundancy.Clone是一个巨大的优势。

任何建议,包括改变我的方法,将不胜感激。

最佳答案

您可以使用 __qualname__ ( PEP 3155 )

>>> class C:
...   def f(): pass
...   class D:
...     def g(): pass
...
>>> C.__qualname__
'C'
>>> C.f.__qualname__
'C.f'
>>> C.D.__qualname__
'C.D'
>>> C.D.g.__qualname__
'C.D.g'

关于python - 获取嵌套类的外部类名称 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173362/

相关文章:

java - 扫描仪再次出现问题

python - 从 python 子进程运行 linux grep 命令

python - 如何读取字典树

c# - 显示不同对象的数组c#(类继承)

ios - 使用双击手势识别器和快速流关闭手势识别器

python - Pyinstaller 创建 Linux 二进制文件时出现以 '\xe8' 开头的非 UTF-8 代码错误

python - 我们可以在 Beautifulsoup 中将所有 XML 标签转换为小写吗

python - 类型错误 : unhashable type: 'list' when calling . iloc()

python - Pandas MultiIndex DataFrame.rolling offset

python - Flask WTForms 表单未提交但未输出验证错误