Can you get the instance variable name from a Python class?
This question already has an answer here:
您可以查看实例的globals
字典并查找将其自身作为值的项目。
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
>>>
Here's a really silly way to do it, if you don't mind the program exiting at that point: add this line to foo():
print undefined_variable
And when you get there, you get a stack trace like this:
Traceback (most recent call last): File "test.py", line 15, in <module> m.foo("Test") File "test.py", line 11, in foo print undefined_variable NameError: global name 'undefined_variable' is not defined
...which tells you that the name of the variable that called it was 'm' :)
(You might be able to do something like this using the traceback
module, without killing the program. I've tried a few ways, but haven't managed to get it to include the m.foo()
line in the output.)
Yes. To get all members of a class, you can use the built in keyword "dir". It will list all the methods and variables in your class. If you use proper naming conversions, you should be able to tell which names are variables and which are methods. Dir returns a list of strings.
class Man():
def __init__(self):
self.name = "Bob"
self.color = "White"
m = Man()
print dir(m)
This will print out:
[' doc ', ' init ', ' module ', 'color', 'name']
Are color and name not the instances variable names of this class?
链接地址: http://www.djcxy.com/p/40940.html上一篇: 以正确的方式打印列表python
下一篇: 你能从Python类获得实例变量名吗?