【问题标题】:In Python, how can you get the name of a member function's class?在 Python 中,如何获取成员函数类的名称?
【发布时间】:2010-09-23 06:50:20
【问题描述】:

我有一个将另一个函数作为参数的函数。如果函数是类的成员,我需要找到该类的名称。例如

def analyser(testFunc):
    print testFunc.__name__, 'belongs to the class, ...

我以为

testFunc.__class__ 

会解决我的问题,但这只是告诉我 testFunc 是一个函数。

【问题讨论】:

    标签: python reflection metaprogramming


    【解决方案1】:

    从 python 3.3 开始,.im_class 消失了。您可以改用.__qualname__。这是相应的 PEP:https://www.python.org/dev/peps/pep-3155/

    class C:
        def f(): pass
        class D:
            def g(): pass
    
    print(C.__qualname__) # 'C'
    print(C.f.__qualname__) # 'C.f'
    print(C.D.__qualname__) #'C.D'
    print(C.D.g.__qualname__) #'C.D.g'
    

    使用嵌套函数:

    def f():
        def g():
            pass
        return g
    
    f.__qualname__  # 'f'
    f().__qualname__  # 'f.<locals>.g'
    

    【讨论】:

      【解决方案2】:
      testFunc.im_class
      

      https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

      im_classim_self 的类 绑定方法或请求的类 对于未绑定方法的方法

      【讨论】:

      • 提示:当你遇到这样的问题时,你可以在你的解释器中使用“dir”来查看 testFunc 有哪个方法,或者更好:ipython tab 补全有帮助!
      • 我的回复总是太迟了。我似乎无法在新文档中找到该用户定义的方法节。 +1
      • 谢谢;您的解决方案适用于我给出的示例。不幸的是,我把我的实际问题简化了太多。我在另一个问题中提出了这个问题:stackoverflow.com/questions/306130/…>
      【解决方案3】:

      我不是 Python 专家,但这行得通吗?

      testFunc.__self__.__class__
      

      它似乎适用于绑定方法,但在您的情况下,您可能使用的是未绑定方法,在这种情况下,这可能会更好:

      testFunc.__objclass__
      

      这是我使用的测试:

      Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) 
      [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
      Type "help", "copyright", "credits" or "license" for more information.
      >>> import hashlib
      >>> hd = hashlib.md5().hexdigest
      >>> hd
      <built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>
      >>> hd.__self__.__class__
      <type '_hashlib.HASH'>
      >>> hd2 = hd.__self__.__class__.hexdigest
      >>> hd2
      <method 'hexdigest' of '_hashlib.HASH' objects>
      >>> hd2.__objclass__
      <type '_hashlib.HASH'>
      

      哦,是的,还有一件事:

      >>> hd.im_class
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
      >>> hd2.im_class
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      AttributeError: 'method_descriptor' object has no attribute 'im_class'
      

      所以如果你想要一些防弹的东西,它也应该处理__objclass____self__。但您的里程可能会有所不同。

      【讨论】:

      • 不,这会给您消息:“AttributeError: 'function' object has no attribute 'self'”。
      • 试试 objclass 属性,看看是否有效。如果是这样,那么你的函数是未绑定的。
      【解决方案4】:

      实例方法将具有属性 .im_class .im_func .im_self

      http://docs.python.org/library/inspect.html#types-and-members

      您可能想查看函数是否有attr .im_class,并从那里获取类信息。

      【讨论】:

        【解决方案5】:

        请使用以下函数获取类中的方法名称

        def getLocalMethods(clss):
        import types
        # This is a helper function for the test function below.
        # It returns a sorted list of the names of the methods
        # defined in a class. It's okay if you don't fully understand it!
        result = [ ]
        for var in clss.__dict__:
            val = clss.__dict__[var]
            if (isinstance(val, types.FunctionType)):
                result.append(var)
        return sorted(result)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          相关资源
          最近更新 更多