【问题标题】:How can one locate where an inherited variable comes from in Python?如何在 Python 中找到继承变量的来源?
【发布时间】:2016-04-12 02:44:54
【问题描述】:

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

父.py

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

child.py

from parent import parent
class child(parent):
    pass

孙子.py

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

尝试通过函数调用来定位 findMe 变量的来源。

【问题讨论】:

  • ...当您说possibly calling some sort of function 时,您也不希望该函数向上导航继承层次结构,对吧?

标签: python class variables multiple-inheritance


【解决方案1】:

如果“变量”是一个实例变量 - ,那么,如果在 __init__ 方法链中的任何一点,你会这样做:

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

从那时起,它就是一个实例变量,并且在所有效果上都不能与任何其他实例变量区分开来。 (除非您设置了一种机制,例如具有特殊 __setattr__ 方法的类,它将跟踪属性更改,并反省代码的哪一部分设置了属性 - 请参阅此答案的最后一个示例)

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

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

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

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

class parent(object):
    findMe = False

class childone(parent):
    ...

可以通过自省 MRO(方法解析顺序)链中的每个类的 __dict__ 来找到定义 findMe 的类。当然,如果不自省 MRO 链中的所有类,就没有办法,也没有任何意义 - 除非有人跟踪定义的属性,如下面的示例 - 但自省 MRO 本身是蟒蛇:

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

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

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

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

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 definitions 和实例 _definitions 字典中的类属性——因为在每个创建instance 一个任意方法可能是最后一个设置特定实例属性的方法:(这是纯 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)

上面代码的示例类:

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' 

【讨论】:

  • Jsbueno,非常感谢您的详细解释。这个回复完全回答了我关于这个的问题。我的意思是放 self.findMe,但是当我提交它时,它删除了它。正是我想要的。再次感谢!
猜你喜欢
  • 2013-07-17
  • 2023-02-09
  • 1970-01-01
  • 2018-02-24
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2011-09-21
相关资源
最近更新 更多