如何在 Python 中找到继承变量的来源?

How can one locate where an inherited variable comes from in Python?

如果你有多层继承并且知道一个特定的变量存在,有没有办法追溯到变量起源的地方?无需通过查看每个文件和 类 向后导航。可能调用某种函数来做到这一点? 示例:

parent.py

class parent(object):
    def __init__(self):
        findMe = "Here I am!"

child.py

from parent import parent
class child(parent):
    pass

grandson.py

from child import child
class grandson(child):
    def printVar(self):
        print self.findMe

尝试通过函数调用找到 findMe 变量的来源。

如果 "variable" 是一个实例变量 - ,那么,如果在 __init__ 方法链中的任何一点你做:

def __init__(self):
    self.findMe = "Here I am!"

从那时起它就是一个实例变量,并且就所有效果而言,它不能与任何其他实例变量区分开来。 (除非你建立了一个机制,比如 class 和一个特殊的 __setattr__ 方法,它会跟踪属性的变化,并反省代码的哪一部分设置了属性 - 请参见上一个示例这个答案)

另请注意,在您的示例中,

class parent(object):
    def __init__(self):
        findMe = "Here I am!"

findMe 被定义为该方法的局部变量,在 __init__ 完成后甚至不存在。

现在,如果您的变量被设置为继承链某处的 class 属性:

class parent(object):
    findMe = False

class childone(parent):
    ...

可以通过内省 MRO(方法解析顺序)链中的每个 class' __dict__ 来找到 class,其中 findMe 是定义的。当然,如果不对 MRO 链中的所有 classes 进行内省,这样做是没有办法,也没有任何意义的——除非有人按照定义跟踪属性,就像下面的例子一样——但要对 MRO 进行内省本身是 Python:

中的一个 oneliner
def __init__(self):
    super().__init__()
    ...
    findme_definer = [cls for cls in self.__class__.__mro__ if "findMe" in cls.__dict__][0]

同样 - 您的继承链可以有一个元class,它将跟踪继承树中所有定义的属性,并使用字典检索每个属性的定义位置。同样的 metaclass 也可以自动修饰所有 __init__ (或所有方法),并设置一个特殊的 __setitem__ 以便它可以在创建实例属性时跟踪它们,如上所列。

这是可以做到的,有点复杂,难以维护,并且可能表明您对问题采取了错误的方法。

因此,仅记录 class 属性的 metaclass 可以简单地是 (python3 语法 - 在 class 主体上定义一个 __metaclass__ 属性如果您仍在使用 Python 2.7):

class MetaBase(type):
    definitions = {}
    def __init__(cls, name, bases, dct):
        for attr in dct.keys():
            cls.__class__.definitions[attr] = cls

class parent(metaclass=MetaBase):
    findMe = 5
    def __init__(self):
        print(self.__class__.definitions["findMe"])

现在,如果要查找哪个超class定义了当前class的属性,只需一个"live"跟踪机制,将每个方法包装在每个class 可以工作 - 它更棘手。

我做到了 - 即使您不需要这么多,这结合了两种方法 - 跟踪 class'class [=] 中的 class 属性27=] 和实例 _definitions 字典 - 因为在每个创建的实例中,任意方法可能是最后一个设置特定实例属性的方法:(这是纯粹的 Python3,也许不是那么直截了当由于 Python2 使用的 "unbound method" 移植到 Python2,并且是 Python3)

中的一个简单函数
from threading import current_thread
from functools import wraps
from types import MethodType
from collections import defaultdict

def method_decorator(func, cls):
    @wraps(func)
    def wrapper(self, *args, **kw):
        self.__class__.__class__.current_running_class[current_thread()].append(cls)
        result = MethodType(func, self)(*args, **kw)
        self.__class__.__class__.current_running_class[current_thread()].pop()
        return result
    return wrapper

class MetaBase(type):
    definitions = {}
    current_running_class = defaultdict(list)
    def __init__(cls, name, bases, dct):
        for attrname, attr in dct.items():
            cls.__class__.definitions[attr] = cls
            if callable(attr) and attrname != "__setattr__":
                setattr(cls, attrname, method_decorator(attr, cls))

class Base(object, metaclass=MetaBase):
    def __setattr__(self, attr, value):
        if not hasattr(self, "_definitions"):
            super().__setattr__("_definitions", {})
        self._definitions[attr] = self.__class__.current_running_class[current_thread()][-1]
        return super().__setattr__(attr,value)

上述代码的示例 类:

class Parent(Base):
    def __init__(self):
        super().__init__()
        self.findMe = 10

class Child1(Parent):
    def __init__(self):
        super().__init__()
        self.findMe1 = 20

class Child2(Parent):
    def __init__(self):
        super().__init__()
        self.findMe2 = 30

class GrandChild(Child1, Child2):
    def __init__(self):
        super().__init__()
    def findall(self):
        for attr in "findMe findMe1 findMe2".split():
            print("Attr '{}' defined in class '{}' ".format(attr, self._definitions[attr].__name__))

在控制台上会得到这样的结果:

In [87]: g = GrandChild()

In [88]: g.findall()
Attr 'findMe' defined in class 'Parent' 
Attr 'findMe1' defined in class 'Child1' 
Attr 'findMe2' defined in class 'Child2'