如何从 Python 函数或方法中获取函数或方法的名称? [英] How do I get the name of a function or method from within a Python function or method?

查看:45
本文介绍了如何从 Python 函数或方法中获取函数或方法的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我应该知道这一点,但我一直无法弄清楚...

I feel like I should know this, but I haven't been able to figure it out...

我想从方法内部获取方法的名称(恰好是集成测试),以便它可以打印出一些诊断文本.当然,我可以在字符串中硬编码方法的名称,但如果可能的话,我想让测试更干一些.

I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

推荐答案

涉及通过inspect 进行自省的答案是合理的.但可能还有另一种选择,具体取决于您的情况:

The answers involving introspection via inspect and the like are reasonable. But there may be another option, depending on your situation:

如果您的集成测试是使用 unittest 模块编写的,那么您可以使用 self.id() 在您的测试用例中.

If your integration test is written with the unittest module, then you could use self.id() within your TestCase.

这篇关于如何从 Python 函数或方法中获取函数或方法的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆