python - 从对象内部获取分配给该对象的变量?

标签 python python-3.x class introspection

在Python中,我想获取正在分配对象的变量。类似于:

class Parent(object):

    def __init__(self):
        print(???) # Print the variable to which the created instance of 
                   # Parent has been assigned to. 

p = Parent() # This should print 'p'. 

我想出了这个:

import inspect


class Parent(object):

    def __init__(self):
        print((inspect.stack()[-1].code_context[-1].split()[0]))


p = Parent()

如果我理解正确的话,它实际上是查看最外层的调用,并获取左侧的字符串部分,这恰好是变量 - 但对我来说,这看起来很奇怪。有没有更好的办法?

最佳答案

是的,您可以做到这一点,使用inspectast来解析源代码,您可以使用inspect找到它.stack().

请注意,您的解决方案为我打印 "__main__",,并且我正在 Python 3.5.2 上进行测试,因此其他 Python 版本的答案可能略有不同。

import inspect
import ast

class Parent(object):

    def __init__(self):
        frame = inspect.stack()[1]
        # Parse python syntax of the assignment line
        st = ast.parse(frame.code_context[0].strip())
        stmt = st.body[0]
        # Assume class being instanced as simple assign statement
        assert(isinstance(stmt, ast.Assign))
        # Parse the target the class is assigned to
        target = stmt.targets[0]
        print(target.id) # prints "p"

p = Parent()

这只适用于简单的赋值语句。如果您有更复杂的赋值语句,例如 p, n = Parent(), 0,您将需要添加更多步骤来解析 AST。原则上,所有涉及 Parent() 的有效语句都可以被解析,但在某些情况下不涉及赋值(例如 Parser())。

因此,上面列出的代码只能作为如何解决问题的示例,而不是完整的解决方案。

关于python - 从对象内部获取分配给该对象的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930317/

相关文章:

python - 拆分数据时使用 scikit-learn 规范化 PCA

python - 关于在 vs 代码中为 python 添加一个片段

python - 从列表中删除重复项并检查 IP 是否来自一个列表中的另一个列表

c++ - 对象已经定义

python - 从图像中提取文本

python - 将 spark 数据框列传递给 geohash 函数 - pyspark。无法将列转换为 bool :

python - 为什么返回的函数没有被赋值却没有报错?

python - 如何从字符串列表中获取少数特定字符串?

CSS - 在类中设置多个 id

Java - 为什么 ClassName.this.variable 在变量为静态时起作用?