【问题标题】:Dynamic/static analysis of method resolution order in PythonPython中方法解析顺序的动态/静态分析
【发布时间】:2018-05-22 11:07:34
【问题描述】:

有没有一种方法可以让我在运行时或通过静态分析务实地确定给定 python 类的method resolution order

假设我有一组类

class A():
    ...

class B(A):
    ...

class C(A):
    ...

class D(B, C):
    def print_mro(self):
         print("D, B, C, A")

我想找出它们的 C3 线性化是不是不必通过源代码来查找并尝试手动确定顺序。我正在开发一个 django 应用程序,其中的视图有很多 mixin,到目前为止,它们的顺序相当随意。我需要确保它们的顺序正确,出于安全原因,我不想 手动检查我的工作并冒着数据泄露的风险。我也不想手动遍历并在每个 mixin 的 dispatch 方法中添加一个 print 语句。

【问题讨论】:

    标签: python-3.x python-mro


    【解决方案1】:

    怎么样

    class A():
        pass
    
    class B(A):
       pass
    
    class C(A):
        pass
    
    class D(B, C):
        def print_mro(self):
             print(self.__class__.__mro__)
    
    d = D()
    d.print_mro()
    

    ?

    【讨论】:

      【解决方案2】:

      你也可以-

      d = D()
      print(help(d))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 2018-12-01
        • 2018-05-07
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多