在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()
如果我理解正确的话,它实际上是查看最外层的调用,并获取左侧的字符串部分,这恰好是变量 - 但对我来说,这看起来很奇怪。有没有更好的办法?
最佳答案
是的,您可以做到这一点,使用inspect
和ast
来解析源代码,您可以使用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/