如何区分Python中的类和静态方法并返回一个布尔值

时间:2017-03-22 18:33:45

标签: python

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。)

4 个答案:

答案 0 :(得分:1)

The types are simply classmethod and staticmethod, so if you want to perform type or isinstance checks, classmethod and staticmethod are the types to use.

答案 1 :(得分:1)

The inspect module seems to give the desired result:

import inspect

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

The first returns True, while the latter returns False.

Or using types:

import types

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

答案 2 :(得分:1)

You want:

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

And using vars(my_object) is just a cleaner way of accessing my_object.__dict__

答案 3 :(得分: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

干杯!