如何获取作为param传递的方法的全名

2024-04-24 09:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定这是不是一个重复的问题。我在网上阅读信息(包括这里,例如How to get a function name as a string in Python?)和各种各样的建议,但各种信息要么是过时的/不是针对我的特定用例的/我只是在错误地实现它。你知道吗

问题是:

我将对象的方法作为参数传递。我想知道这个对象和方法的全名是什么。你知道吗

示例代码(到目前为止我所处的位置):

class test():
  def asdf():
    print('asdf')

def magic(command):
  print('command is:', command.__name__)

magic(test.asdf)

目标是从magic()输出'command is:asdf'到'command is:测试.asdf'因为这是参数的全名。你知道吗


Tags: to对象方法nametest信息getis
2条回答

使用__qualname__。你知道吗

>>> print(test.asdf.__qualname__)
test.asdf

要清楚的是,传递的不是“对象的方法作为参数”,而是类定义中的函数名。你知道吗

要传递“对象的方法”,必须实际创建一个对象,代码如下所示:

class test():
  def asdf():
    print('asdf')

def magic(command):
  print('command is:', command.__func__.__qualname__)
  # Returning the object to which this method is bound just to ilustrate
  return command.__self__

magic(test().asdf)

“对象的方法”=Instance methods

相关问题 更多 >