【问题标题】:How to distinguish between class and static methods in Python and return a Boolean如何区分 Python 中的类和静态方法并返回布尔值
【发布时间】:2017-03-22 18:33:44
【问题描述】:

类似于How to distinguish an instance method, a class method, a static method or a function in Python 3?,我想判断给定的方法是类方法还是静态方法。

在该答案中,描述了如何打印type 以确定这一点。例如,

class Resource(object):
    @classmethod
    def parse_class(cls, string):
        pass

    @staticmethod
    def parse_static(string):
        pass

# I would like to turn these print statements into Booleans
print type(Resource.__dict__['parse_class'])
print type(Resource.__dict__['parse_static'])

打印输出

<type 'classmethod'>
<type 'staticmethod'>

不过,我想更进一步,写一个布尔表达式来判断一个方法是类还是静态方法。

有什么想法可以解决这个问题吗? (我看过 types 模块,但没有一个类型看起来像 classmethodstaticmethod)。

【问题讨论】:

  • 也许我误解了你,但你只是想将静态方法的类型分配给一个变量以便与你的方法进行比较吗? type(staticmethod(None))

标签: python


【解决方案1】:

关键字staticmethodclassmethod代表同名类型:

In [1]: staticmethod.__class__
Out[1]: type

In [2]: type(staticmethod)
Out[2]: type

In [3]: classmethod.__class__
Out[3]: type

In [4]: type(classmethod)
Out[4]: type

这意味着您可以使用它们来比较您在示例中打印的语句:

In [5]: class Resource(object):
   ...:     @classmethod
   ...:     def parse_class(cls, string):
   ...:         pass
   ...: 
   ...:     @staticmethod
   ...:     def parse_static(string):
   ...:         pass
   ...:     

 In [6]: print type(Resource.__dict__['parse_class']) == classmethod
 True

 In [7]: print type(Resource.__dict__['parse_static']) == staticmethod
 True

干杯!

【讨论】:

    【解决方案2】:

    类型只是classmethodstaticmethod,所以如果你想执行typeisinstance检查,classmethodstaticmethod是要使用的类型。

    【讨论】:

      【解决方案3】:

      你想要:

      isinstance(vars(Resource)['parse_class'], classmethod)
      isinstance(vars(Resource)['parse_static'], staticmethod)
      

      使用vars(my_object) 只是访问my_object.__dict__ 的一种更简洁的方式

      【讨论】:

        【解决方案4】:

        inspect 模块似乎给出了预期的结果:

        import inspect
        
        inspect.ismethod(Resource.parse_class)
        inspect.ismethod(Resource.parse_static)
        

        第一个返回True,而后者返回False

        或者使用types:

        import types
        
        isinstance(Resource.parse_class, MethodType)
        isinstance(Resource.parse_static, MethodType)
        

        【讨论】:

        • 为什么只有似乎才能给出想要的结果?
        • 这可能不是你认为的那样。描述符协议将Resource.parse_static 解析为类主体中定义的实际parse_static 函数,而Resource.parse_class 解析为绑定的方法对象。事情以这种方式发展有点侥幸,而且这不是实现预期目标的非常明确的方法。
        • @user2358112: type(Resource.parse_class) -> instancemethod vs type(Resource.parse_static) -> function
        • 如果你希望第二个布尔值也是True,你应该做type(Resource.parse_static) == types.FunctionType
        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        相关资源
        最近更新 更多