Can you get the instance variable name from a class? [duplicate]

让人想犯罪 __ 提交于 2021-01-26 19:06:45

问题


I understand that you should never use variable names within the program, but I am using is strictly for debug purposes and would like to convey the name of the variable to the user for readability.

I have a file like this:

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")

I would like to retrieve the m instance variable name from within the class itself. Though this is merely an example file, I am using it to convey to the user that a raw socket has been created at a certain attribute within an instance variable, and would like to show where it is (i.e. New socket at m.socket)

Is this feasible with Python?


回答1:


You could look in the instance's globals dictionary and find the item that has its self as a value.

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
>>> 



回答2:


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.)




回答3:


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?



来源:https://stackoverflow.com/questions/32163330/can-you-get-the-instance-variable-name-from-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!