检查方法是否是静态的

检查方法是否是静态的

本文介绍了Python:检查方法是否是静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下类定义:

class A:
  def f(self):
    return 'this is f'

  @staticmethod
  def g():
    return 'this is g'

a = A()

所以 f 是普通方法,g 是静态方法.

So f is a normal method and g is a static method.

现在,我如何检查功能对象 a.f 和 a.g 是否是静态的?Python 中是否有isstatic"函数?

Now, how can I check if the funcion objects a.f and a.g are static or not? Is there a "isstatic" funcion in Python?

我必须知道这一点,因为我有包含许多不同函数(方法)对象的列表,要调用它们,我必须知道它们是否期望将self"作为参数.

I have to know this because I have lists containing many different function (method) objects, and to call them I have to know if they are expecting "self" as a parameter or not.

推荐答案

我正好有一个模块可以解决这个问题.它是Python2/3 兼容解决方案.并且它允许使用从父类继承的方法进行测试.

I happens to have a module to solve this. And it's Python2/3 compatible solution. And it allows to test with method inherit from parent class.

另外,这个模块还可以测试:

Plus, this module can also test:

  1. 常规属性
  2. 属性样式方法
  3. 常规方法
  4. 静态方法
  5. 类方法

例如:

class Base(object):
    attribute = "attribute"

    @property
    def property_method(self):
        return "property_method"

    def regular_method(self):
        return "regular_method"

    @staticmethod
    def static_method():
        return "static_method"

    @classmethod
    def class_method(cls):
        return "class_method"

class MyClass(Base):
    pass

这是仅限静态方法的解决方案.但是我建议使用该模块在此处发布.

Here's the solution for staticmethod only. But I recommend to use the module posted here.

import inspect

def is_static_method(klass, attr, value=None):
    """Test if a value of a class is static method.

    example::

        class MyClass(object):
            @staticmethod
            def method():
                ...

    :param klass: the class
    :param attr: attribute name
    :param value: attribute value
    """
    if value is None:
        value = getattr(klass, attr)
    assert getattr(klass, attr) == value

    for cls in inspect.getmro(klass):
        if inspect.isroutine(value):
            if attr in cls.__dict__:
                bound_value = cls.__dict__[attr]
                if isinstance(bound_value, staticmethod):
                    return True
    return False

这篇关于Python:检查方法是否是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:21