Goo*_*ies 7 python class instance-variables instance
我知道你不应该在程序中使用变量名,但我使用的是严格的调试目的,并希望将变量的名称传达给用户以提高可读性。
我有一个这样的文件:
class MyClass(object):
def __init__(self):
pass
def foo(msg=""):
debug("Called from the %s instance.") #quazi-print function that only prints when a DEBUG variable is True.
print(msg)
m = MyClass()
m.foo("Test")
Run Code Online (Sandbox Code Playgroud)
我想m从类本身中检索实例变量名称。虽然这只是一个示例文件,但我使用它向用户传达已在实例变量中的某个属性处创建了原始套接字,并希望显示它的位置(即New socket at m.socket)
这对 Python 可行吗?
您可以查看实例的globals字典并找到以其 self 作为值的项目。
class Foo(object):
def bar(self):
return [k for k,v in globals().items() if v is self]
def bah(self):
d = {v:k for k,v in globals().items()}
return d[self]
f = Foo()
g = Foo()
print f.bar(), g.bar()
print f.bah(), g.bah()
>>>
['f'] ['g']
f g
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11039 次 |
| 最近记录: |