你能从Python类中获取实例变量名吗? [重复]

时间:2022-08-25 23:23:27

This question already has an answer here:

这个问题在这里已有答案:

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)

我想从类本身中检索“m”实例变量名。虽然这只是一个示例文件,但我用它来向用户传达一个原始套接字已经在一个实例变量中的某个属性上创建,并希望显示它在哪里(即m.socket上的新套接字)

Is this feasible with Python?

这对Python有用吗?

3 个解决方案

#1


1  

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

您可以查看实例的全局字典并找到将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
>>> 

#2


1  

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():

这是一个非常愚蠢的方法,如果你不介意在那一点退出程序:将这一行添加到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

回溯(最近一次调用最后一次):文件“test.py”,第15行,在 m.foo(“Test”)文件“test.py”,第11行,在foo中打印undefined_variable NameError:全局名称'undefined_variable ' 没有定义

...which tells you that the name of the variable that called it was 'm' :)

...告诉你调用它的变量的名称是'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.)

(你可能可以使用traceback模块做这样的事情,而不会杀死程序。我已经尝试了几种方法,但没有设法让它在输出中包含m.foo()行。)

#3


0  

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.

是。要获取类的所有成员,可以使用内置关键字“dir”。它将列出您班级中的所有方法和变量。如果使用正确的命名转换,您应该能够确定哪些名称是变量,哪些是方法。 Dir返回一个字符串列表。

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

['doc','init','module','color','name']

Are color and name not the instances variable names of this class?

颜色和名称不是此类的实例变量名称吗?

#1


1  

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

您可以查看实例的全局字典并找到将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
>>> 

#2


1  

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():

这是一个非常愚蠢的方法,如果你不介意在那一点退出程序:将这一行添加到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

回溯(最近一次调用最后一次):文件“test.py”,第15行,在 m.foo(“Test”)文件“test.py”,第11行,在foo中打印undefined_variable NameError:全局名称'undefined_variable ' 没有定义

...which tells you that the name of the variable that called it was 'm' :)

...告诉你调用它的变量的名称是'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.)

(你可能可以使用traceback模块做这样的事情,而不会杀死程序。我已经尝试了几种方法,但没有设法让它在输出中包含m.foo()行。)

#3


0  

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.

是。要获取类的所有成员,可以使用内置关键字“dir”。它将列出您班级中的所有方法和变量。如果使用正确的命名转换,您应该能够确定哪些名称是变量,哪些是方法。 Dir返回一个字符串列表。

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

['doc','init','module','color','name']

Are color and name not the instances variable names of this class?

颜色和名称不是此类的实例变量名称吗?