【问题标题】:How to distinguish an instance method, a class method, a static method or a function in Python 3?Python 3 中如何区分实例方法、类方法、静态方法或函数?
【发布时间】:2013-11-25 15:54:38
【问题描述】:

我想区分Python 3中的方法和函数。此外,如果是方法,我想获取对应的类。我目前的解决方案是这样的:

import types
import inspect

def function_or_method(f):
    if inspect.ismethod(f):
        if inspect.isclass(f.__self__):
            print("class method")
            klass = f.__self__
        else:
            print("instance method")
            klass = f.__self__.__class__
    elif inspect.isfunction(f): # function
        if f.__name__ != f.__qualname__: # to distiguish staticmethod and function
            print("static method")
            # HOW TO GET THE CLASS
        else:
            print("function")
    else:
        print("not function or method")

class Foo():
    def bari(self):
        pass
    @classmethod
    def barc(cls):
        pass
    @staticmethod
    def bars():
        pass

def barf():
    pass

function_or_method(Foo().bari) # instance method
function_or_method(Foo.barc) # class method
function_or_method(Foo.bars) # static method
function_or_method(barf) # function

它有效,但看起来并不优雅。而且我不确定我是否错过了什么。有谁知道更好的解决方案?

UPDATE 1:如果是方法,我也想获取对应的类。我知道如何处理类/实例方法(参见上面的代码),但是如何获取静态方法的类?

【问题讨论】:

    标签: python python-3.x introspection


    【解决方案1】:

    我认为更好的方法是使用inspectisfunction() 方法。

    语法:

    [inspect.getmembers(<module name>, inspect.isfunction)] # will give all the functions in that module
    

    如果你想测试单个方法,你可以通过......

    inspect.isfunction(<function name>) # return true if is a function else false
    

    有许多谓词可以与 is 函数一起使用。请参阅inspect 的 Python 3 文档以获得清晰的图片。

    【讨论】:

      【解决方案2】:

      你只需要获取方法的类型,但是由于方法是描述符,你必须:

      1 - 从实例中获取类。 2 - 在__dict__ 中查找方法引用,而不是进行属性查找。

      E.G:

      >>> f = Foo()
      >>> type(f.__class__.__dict__['bari'])
      <class 'function'>
      >>> type(f.__class__.__dict__['barc'])
      <class 'classmethod'>
      >>> type(f.__class__.__dict__['bars'])
      <class 'staticmethod'>
      

      【讨论】:

        猜你喜欢
        • 2018-03-07
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        相关资源
        最近更新 更多