【问题标题】:Getting name of passed in function [duplicate]获取传入函数的名称[重复]
【发布时间】:2015-11-28 18:40:23
【问题描述】:

好的,所以我有一个将函数作为参数的函数。

我想附加已经传入的函数的实际名称(不是成员)...

def a_specially_named_function(g):
    return ()

def analyze_function(function):
    print ...


analyze_function(a_specially_named_function)
>>> "a_specially_named_function"

我该怎么做?在 .NET 中,我相信我会使用反射...我想这样做而无需添加成员或任何东西...

【问题讨论】:

    标签: python


    【解决方案1】:

    有一个名为.__name__

    魔法场
    def a_specially_named_function(g):
        return ()
    
    def analyze_function(function):
        print function.__name__
    
    
    analyze_function(a_specially_named_function)
    >>> a_specially_named_function
    

    此外,您可以使用 dir 函数来检查 python 中对象的所有可用字段,包括它的 magic 成员

    dir(a_specially_named_function)
    >>> ['__call__', '__class__', '__closure__', '__code__', 
         '__defaults__', '__delattr__', '__dict__', '__doc__',
         '__format__', '__get__', '__getattribute__', '__globals__',
         '__hash__', '__init__', '__module__', '__name__', '__new__', 
         '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
         '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 
         'func_code', 'func_defaults', 'func_dict', 'func_doc', 
         'func_globals', 'func_name']
    

    【讨论】:

    • 好的,太棒了,谢谢!
    • 这不是万无一失的。定义foo,然后foo.__name__"foo",正如预期的那样。但是bar = foobar.__name__NOT "bar",但"foo" 仍然。我不知道你所说的“魔法场”是什么意思,但它不是那种魔法。
    • @Spacedman:这很神奇,因为它是自动发生的。当您执行bar = foo 时,您不会定义新函数,而只是声明对foo 的新引用。所以希望bar.__name__ foo: 所有对同一个对象的引用都表现相同。
    • @Spacedman 我称它们为 magic 因为它们在 python 社区中是这样称呼的 rafekettler.com/magicmethods.html diveintopython3.net/special-method-names.html stackoverflow.com/questions/1090620/…
    • @Spacedman ,此外,bar.__name__ 应该是 foo,正如 Serge 解释的那样。 __name__ 是函数的名称,而不是变量的名称(通过输入 bar = foo,您只需创建一个包含对函数的引用的变量)
    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多