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

Kry*_*n36 2 python variables class multiple-inheritance

如果您有多个继承层并且知道存在特定变量,是否有办法追溯到变量的起源位置?无需通过查看每个文件和类来向后导航.可能会调用某种功能吗?例:

parent.py

class parent(object):
    def __init__(self):
        findMe = "Here I am!"
Run Code Online (Sandbox Code Playgroud)

child.py

from parent import parent
class child(parent):
    pass
Run Code Online (Sandbox Code Playgroud)

grandson.py

from child import child
class grandson(child):
    def printVar(self):
        print self.findMe
Run Code Online (Sandbox Code Playgroud)

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

jsb*_*eno 5

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

def __init__(self):
    self.findMe = "Here I am!"
Run Code Online (Sandbox Code Playgroud)

它是从该点开始的实例变量,并且对于所有效果,不能使其与任何其他实例变量不同.(除非你设置一个机制,比如一个带有特殊__setattr__方法的类,它将跟踪属性的变化,并反省代码的哪一部分设置属性 - 参见本答案的最后一个例子)

请注意,在您的示例中,

class parent(object):
    def __init__(self):
        findMe = "Here I am!"
Run Code Online (Sandbox Code Playgroud)

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

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

class parent(object):
    findMe = False

class childone(parent):
    ...
Run Code Online (Sandbox Code Playgroud)

findMe通过__dict__在MRO(方法解析顺序)链中内省每个类,可以找到定义的类.当然,在没有内省MRO链中的所有类的情况下,没有办法也没有任何意义 - 除非一个人按照定义跟踪属性,比如下面的示例 - 但是内省MRO本身就是一个oneliner蟒蛇:

def __init__(self):
    super().__init__()
    ...
    findme_definer = [cls for cls in self.__class__.__mro__ if "findMe" in cls.__dict__][0]
Run Code Online (Sandbox Code Playgroud)

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

这可以做到,有点复杂,难以维护,并且可能是你对问题采取错误方法的信号.

因此,仅记录类属性的元类可能只是(python3语法 - __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"])
Run Code Online (Sandbox Code Playgroud)

现在,如果想要找到哪个超类定义了当前类的属性,只是一个"实时"跟踪机制,在每个类中包装每个方法都可以工作 - 这要复杂得多.

我已经做到了 - 即使你不需要这么多,它结合了两种方法 - 在类的类definitions和实例_definitions字典中跟踪类属性- 因为在每个创建的实例中,任意方法可能是最后一个设置一个特定的实例属性:(这是纯Python3,由于Python2使用的"未绑定方法",可能不是直接移植到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)
Run Code Online (Sandbox Code Playgroud)

示例上面代码的类:

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__))
Run Code Online (Sandbox Code Playgroud)

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

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' 
Run Code Online (Sandbox Code Playgroud)